I'm working with Bluebird for promises in Node.Js, and was wondering how can I make a function return when the promise is fulfilled(completed).The behavior I want is :
function getItem(){
functionReturningPromise.then(function(result){
//do some operation on result
return result;
});
}
However, the above implementation won't return anything since the promise isn't completed at the time of execution. What would be the best workaround around this?
The purpose of getItem is to modify whatever functionReturningPromise returns, and then return it
The keyword await is used to wait for a Promise. It can only be used inside an async function. This keyword makes JavaScript wait until that promise settles and returns its result.
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.
Using Promise.all()Promise.all waits for all fulfillments (or the first rejection).
No. It is not safe to resolve/reject promise multiple times. It is basically a bug, that is hard to catch, becasue it can be not always reproducible.
You can't, var value = someAsyncFunction()
is not possible (until we have generators, at least). Promises are viral, once you use a Promise in a function, its caller must use then
and the caller of the caller too, etc up to your main program. So, in the function that calls getItem
you have to change this
item = getItem();
do something with item
into this
getItem().then(function(item) {
do something with item
})
and getItem
should return a Promise as well
function getItem(){
return functionReturningPromise().then(function(result){
//do some operation on result
return result;
});
}
(Theoretically it can also be a callback, but I prefer to always return promises).
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