Wednesday, 26 April 2017

then() callback firing before promise is resolved in node.js

Using node.js version 7.7.2, I'd like to execute an asynchronous function and then a different function once the first function has completed like this:

function foo() {
  return new Promise(function(resolve, reject) {
    // Do some async stuff
    console.log('foo is about to resolve');
    resolve();
  });
}

function bar() {
  console.log('bar has fired');
}

foo().then(bar());

The issue is that this setup prints 'bar has fired' followed by 'foo is about to resolve'. What I expect is that bar will wait to fire until the promise returned by foo has resolved. Am I misunderstanding how then() queues callbacks in the node.js event loop?

Thanks



via Allen More

No comments:

Post a Comment