5

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

Allen More
  • 858
  • 3
  • 14
  • 25
  • 2
    because you are calling bar....and assigning what it returns to the then. – epascarello Apr 26 '17 at 20:49
  • 1
    Have you tried it without calling bar explicitly (aka remove the `()`)? – larz Apr 26 '17 at 20:49
  • 1
    Whenever you have `x(y())`, `y` is called *first* and its return value is passed to `x`. This has nothing to do with `.then`, promises or event loops. Arguments are *always* eagerly evaluated. – Felix Kling Apr 26 '17 at 20:49
  • 1
    Gotcha. What if I want to pass parameters into bar? Does that make bar no longer immediately invoked? I'll update the question to reflect this since it more closely represents the issue I'm experiencing. – Allen More Apr 26 '17 at 20:56
  • 1
    `.then` expects a function, so in that case you pass a function that calls `bar` with the parameter: `.then(() => bar('bar has fired'))` – Felix Kling Apr 26 '17 at 21:05
  • Ah, I understand now. Thanks for your help. – Allen More Apr 26 '17 at 21:10

1 Answers1

4

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')});
larz
  • 5,724
  • 2
  • 11
  • 20