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.
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.
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.
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.
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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With