then()在node.js中解析promise之前的回调触发 [英] then() callback firing before promise is resolved in node.js
问题描述
使用node.js版本7.7.2,我想执行一个异步函数,然后在第一个函数完成后执行不同的函数,如下所示:
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'));
问题是此设置打印'bar已解雇'后跟'foo即将解决。我期待的是,在foo返回的承诺得到解决之前,酒吧将等待开火。我是否误解了then()如何在node.js事件循环中对回调进行排队?
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?
谢谢
推荐答案
如评论中所述,将函数传递给然后
,当调用时,将调用 bar
使用你的参数。
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')});
这篇关于then()在node.js中解析promise之前的回调触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!