javascript - Promise 解析中的异步与 then

标签 javascript promise async-await

在下面的代码中,我将 Promise.then() 一起使用,但它不会等待 setTimeout() > 正如我所料。

为什么async/await要等待setTimeout()?看起来 await 会等待 Promise 解析,但 .then() 不会。有人可以提供一些详细信息吗?

function hello() {
  console.log('hello');
}

function myPromiseFunction() {
  return new Promise((resolve, reject) => {
    setTimeout(function() {
      console.log('hey');
      resolve();
    }, 2000);
  });
}

myPromiseFunction().then(hello());  // Prints 'hello' then 'hey'

async function myAsyncFunction() {
  await myPromiseFunction();
  hello();
}

myAsyncFunction();  // Prints 'hey' then 'hello'

最佳答案

myPromiseFunction().then(hello()) 使用调用 hello() 的结果作为 .then() 的回调。如果您希望使用 hello() 作为回调函数本身,请使用以下语法之一:

myPromiseFunction().then(() => hello());
myPromiseFunction().then(hello);

请注意,第二个语法以静默方式将参数传递给 hello() - 由 Promise 解析的值。在您的示例中,这不是问题(因为 hello() 根本不检查使用其参数),但它可能是导致问题的原因。

关于javascript - Promise 解析中的异步与 then,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54681527/

相关文章:

javascript - Crockford 的 String.supplant 中的正则表达式

javascript - Node JS 试图将访问 token 分配给变量

javascript - 使用映射并将对象传递给后续函数调用

c# - 使用异步 CTP 同时下载 HTML 页面

javascript node module.exports/require() 前端代码

javascript - 无法呈现对 html div 的 promise 响应

javascript - 使用 promise 实现超时 - 抛出错误

javascript - 与 bluebird 和 co 一起快速生成生成器功能

javascript - 在异步函数中使用 While 循环?

c# - MVVM XAML 应用程序中的异步等待