close

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

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How do I wait for a promise to finish before returning the variable of a function? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

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

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

    do I wait for a promise to finish before returning the variable of a function 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.

  2. do I wait for a promise to finish before returning the variable of a function

    do I wait for a promise to finish before returning the variable of a function 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.

Method 1

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

Method 2

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(); 

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment