Programming

함수의 변수를 반환하기 전에 약속이 완료되기를 기다리는 방법은 무엇입니까?

procodes 2020. 7. 10. 21:31
반응형

함수의 변수를 반환하기 전에 약속이 완료되기를 기다리는 방법은 무엇입니까?


나는 여전히 약속으로 어려움을 겪고 있지만 여기의 커뮤니티 덕분에 진전이 있습니다.

Parse 데이터베이스를 쿼리하는 간단한 JS 함수가 있습니다. 결과 배열을 반환해야하지만 쿼리의 비동기 특성 (따라서 약속)으로 인해 함수가 결과보다 먼저 반환되어 정의되지 않은 배열을 남겨 둡니다.

이 함수가 약속의 결과를 기다리게하려면 어떻게해야합니까?

내 코드는 다음과 같습니다.

function resultsByName(name)
{   
    var Card = Parse.Object.extend("Card");
    var query = new Parse.Query(Card);
    query.equalTo("name", name.toString());

    var resultsArray = [];

    var promise = query.find({
               success: function(results) {
               // results is an array of Parse.Object.
                             console.log(results);
                             //resultsArray = results;
                             return results;
               },

               error: function(error) {
               // error is an instance of Parse.Error.
                             console.log("Error");
               }
    });                           

}

a resultsArray를 반환하는 대신 결과 배열에 대한 약속을 반환 한 다음 then호출 사이트 에서 약속을 반환 하면 호출자가 함수가 비동기 I / O를 수행한다는 것을 알 수 있습니다. JavaScript의 동시성 코딩은이를 기반으로합니다 . 더 넓은 아이디어를 얻으려면 이 질문읽으십시오 .

function resultsByName(name)
{   
    var Card = Parse.Object.extend("Card");
    var query = new Parse.Query(Card);
    query.equalTo("name", name.toString());

    var resultsArray = [];

    return query.find({});                           

}

// later
resultsByName("Some Name").then(function(results){
    // access results here by chaining to the returned promise
});

Parse의 자체 블로그 게시물 에서 쿼리와 함께 구문 분석 약속을 사용하는 더 많은 예를 볼 수 있습니다 .


이 함수가 약속의 결과를 기다리게하려면 어떻게해야합니까?

사용 async/await(ECMA6의 일부지만, 크롬, 에지, 파이어 폭스와 2017의 말부터 사파리에 해당하는, 참조 canIuse )
MDN

    async function waitForPromise() {
        // let result = await any Promise, like:
        let result = await Promise.resolve('this is a sample promise');
    }

주석으로 인해 추가됨 : 비동기 함수는 항상 Promise를 반환하며 TypeScript에서는 다음과 같습니다.

    async function waitForPromise(): Promise<string> {
        // let result = await any Promise, like:
        let result = await Promise.resolve('this is a sample promise');
    }

You don't want to make the function wait, because JavaScript is intended to be non-blocking. Rather return the promise at the end of the function, then the calling function can use the promise to get the server response.

var promise = query.find(); 
return promise; 

//Or return query.find(); 

You're not actually using promises here. Parse lets you use callbacks or promises; your choice.

To use promises, do the following:

query.find().then(function() {
    console.log("success!");
}, function() {
    console.log("error");
});

Now, to execute stuff after the promise is complete, you can just execute it inside the promise callback inside the then() call. So far this would be exactly the same as regular callbacks.

To actually make good use of promises is when you chain them, like this:

query.find().then(function() {
    console.log("success!");

    return new Parse.Query(Obj).get("sOmE_oBjEcT");
}, function() {
    console.log("error");
}).then(function() {
    console.log("success on second callback!");
}, function() {
    console.log("error on second callback");
});

I have same problem, so I maintain some code, code need call ajax done to process another task, here my code

this.bindChangeEvent = function () {
    //select all bind change
    this._select_all.bind('change', function () {
        console.log('All')
        if ($(this).is(":checked")) {
            ///todo: call ajax to get all ids
            var idsAllItem = pointer.getAllData();

            console.log(idsAllItem);
            console.log('Another todo');

Ajax function

this.getAllData = function() {
    var promises = [];
    var def = new $.Deferred();
    return new Promise((resolve, reject) => {
        // AJAX request
        var url = '...';
        $.ajax({
            url: url,
            type: "get",
            async: true,
            data: {},
            dataType: "json",
            success: function (data) {
                console.log('Ajjax done');
                resolve(data)
            },
            error: function (err) {
                reject(err)
            }
        });
    })
};

and i get result

Another todo
Output
Ajax Done

….

참고 : https://stackoverflow.com/questions/27759593/how-do-i-wait-for-a-promise-to-finish-before-returning-the-variable-of-a-functio

반응형