Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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(arg) {
  console.log(arg);
}

foo().then(bar('bar has fired'));

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

like image 418
Allen More Avatar asked Apr 26 '17 20:04

Allen More


1 Answers

As stated in a comment, pass a function to then that, when called, will call bar with your params.

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

foo().then(function(){bar('bar has fired')});
like image 134
larz Avatar answered Sep 25 '22 10:09

larz