Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an empty promise

Tags:

node.js

promise

q

I have a function in a chain of promises that may or may not do something. E.g.

  getYear().then(function(results){
    if(results.is1999) return party();
    else return Q.fcall(function(){/*do nothing here*/});
  }).then(sleep)

Where getYear, party, and sleep all return promises. Is there a more concise way to write the else statement? That is, do nothing, but still return a chainable promise?

like image 917
prauchfuss Avatar asked May 24 '13 23:05

prauchfuss


People also ask

How do I send an empty promise?

An "empty promise" is another way of saying "a lie" in english.. so having an instantly resolved promise is better, just from a language standpoint ;) Promise. resolve() worked for me! new Promise now requires a parameter, use Promise.

What's an empty promise?

Empty-promise definition (idiomatic) A promise that is either not going to be carried out, worthless or meaningless. noun.


1 Answers

Yes. Q(value) returns a promise for the value (it also unwraps the value if value is a promise).

  getYear().then(function(results){
    if(results.is1999) return party();
    else return Q(undefined);
  }).then(sleep)

Alternatively, you can get the exact same semantics by just not returning anything:

  getYear().then(function(results){
    if(results.is1999) return party();
  }).then(sleep)

If what you wanted was a promise that's never resolved, your best bet would be

  getYear().then(function(results){
    if(results.is1999) return party();
    else return Q.promise(function () {});
  }).then(sleep)

What you could do is re-use the same promise:

  var stop = Q.promise(function () {});
  getYear().then(function(results){
    if(results.is1999) return party();
    else return stop
  }).then(sleep)
like image 84
ForbesLindesay Avatar answered Oct 02 '22 08:10

ForbesLindesay