Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise Js: Wait till promise fulfilled [duplicate]

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

like image 540
Ashwini Khare Avatar asked Mar 03 '16 23:03

Ashwini Khare


People also ask

How do you wait for a promise to be fulfilled?

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.

How do you wait until your promise is resolved?

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.

Does promise all wait for all promises?

Using Promise.all()Promise.all waits for all fulfillments (or the first rejection).

Can you await the same promise multiple times?

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.


1 Answers

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).

like image 86
georg Avatar answered Oct 15 '22 22:10

georg