then() 在 node.js 中解决 promise 之前触发回调 [英] then() callback firing before promise is resolved in node.js

查看:11
本文介绍了then() 在 node.js 中解决 promise 之前触发回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆