12

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

Ashwini Khare
  • 1,645
  • 6
  • 20
  • 37
  • 1
    You can't. If your operation is async, then the result of that operation cannot be returned synchronously, ever. Simply return your promise and have the caller use `.then()` on the promise to get the result. That's how async development works in node.js. – jfriend00 Mar 03 '16 at 23:35

2 Answers2

15

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

georg
  • 211,518
  • 52
  • 313
  • 390
-2

The purpose of getItem is to modify whatever functionReturningPromise returns, and then return it

Then, I think you could simply do

functionReturningPromise.then(getItem);

where

function getItem(valueFromPromiseResolution){
    //do some operation on valueFromPromiseResolution
    return whatever;
}
Dimitris Karagiannis
  • 8,942
  • 8
  • 38
  • 63