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 即将解决".我期望的是 bar 会等到 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?
谢谢
推荐答案
如评论中所述,将一个函数传递给 then
,该函数在调用时将调用 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屋!