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
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')});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With