How do I wait for a promise to finish before returning the variable of a function?

前端 未结 4 487
情话喂你
情话喂你 2020-11-29 23:15

I\'m still struggling with promises, but making some progress thanks to the community here.

I have a simple JS function which queries a Parse database. It\'s suppose

4条回答
  •  醉酒成梦
    2020-11-29 23:58

    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");
    });
    

提交回复
热议问题