Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for a promise to resolve before function returns a value [duplicate]

Tags:

node.js

I'm trying to execute the following code:

exports.myFunction = function(){
    myPromise.doThis().then(ret => {
     return ret;
    });
}

When calling this function it returns undefined. How do I make the function wait for the promise to resolve then return.

like image 260
Simar Avatar asked May 13 '16 02:05

Simar


People also ask

How wait for promise to resolve before returning from function?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.

What happens if you await a promise twice?

The implication of this is that promises can be used to memoize async computations. If you consume a promise whose result will be needed again later: consider holding on to the promise instead of its result! It's fine to await a promise twice, if you're happy to yield twice.

What happens if you don't resolve a promise?

A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object.

Is promise resolve same as return?

The Promise. resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.


1 Answers

Being asynchronous, there is no guarantee of knowing when the promise will be resolved. It may have to wait for a while (depending on what you are doing).

The typical way of continuing execution after a promise is by chaining execution or by using callback functions.

As a Callback

Your sample code (to me) suggests the use of a callback.

exports.myFunction = function(callback){
    myPromise.doThis().then(ret => {
        callback(ret);
    });
}

Then using would look similar to:

var myFunction = require('pathToFile').myFunction;

myFunction(function(ret){
    //Do what's required with ret here
});

Edit:

As @torazaburo mentioned, the function can be condensed into:

exports.myFunction = function(callback){
    myPromise.doThis().then(callback);
} 

As a Promise

exports.myFunction = function(){
    //Returnes a promise
    return myPromise.doThis();
}

Then using would look similar to:

var myFunction = require('pathToFile').myFunction;

myFunction().then(function(ret){
    //Do what's required with ret here
});
like image 97
AXRS Avatar answered Sep 22 '22 05:09

AXRS