Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

q.js: can I stop a function from executing until a promise is fulfilled?

Tags:

node.js

q

As an example:

if(foo) {
    async_call(); // returns a Q promise object
}
// do this immediately if foo was false 
// or after the promise is resolved if foo was true

Is this even possible?

The alternatives I can see are either always calling the async function, throwing out the 'foo' check, which is less optimal but would work in-code; or just assuming that 'foo' is true and throwing an error if it's false (requiring the caller to try again after the calling the async function itself) which is even less ideal for obvious reasons.

EDIT: as a temporary work around, I found this works, but it's hardly ideal:

var promise = foo ? Q.defer().resolve(foo).promise : async_call();
promise.then(function(foo) {
    // this is done after the async call if it was necessary or immediately if not
});
like image 546
Chris Browne Avatar asked Mar 27 '13 10:03

Chris Browne


1 Answers

Q.when() can be used for exactly this, when you don't know if a value is a promise or not.

Q.when(foo || async_call()).then(function (foo) {
  //...
});
like image 88
Andreas Hultgren Avatar answered Nov 15 '22 04:11

Andreas Hultgren