编写承诺的异步/等待版本

Ugur Kaya

下面的代码按预期每秒记录一次“ hello world”。

function moveOneStep() {
  return new Promise((res, rej) => {
    setTimeout(() => {
      res(console.log('Hello world!'))
    }, 1000)
  })  
}

async function main() {
  await moveOneStep();
  await moveOneStep();
  await moveOneStep();
  await moveOneStep();
}

考虑到函数returnasync对应resolve于promise中函数返回,为什么下面的代码不能输出相同的结果,而是立即记录所有“ hello world”:

async function moveOneStepAsync() {
  setTimeout(() => {
    return console.log('Hello world!');
  }, 1000);
}

async function main() {
  await moveOneStepAsync();
  await moveOneStepAsync();
  await moveOneStepAsync();
  await moveOneStepAsync();
}
丹尼尔·古兹(Danil Gudz)

那是因为在您的函数setTimeout中不返回承诺setTimeout本身将同步执行。它在事件循环中添加了作为参数传递的回调,以便在提及的时间及时执行。awaitmain

同样在此代码中,回调的返回并不意味着回调将在1秒钟内运行,并且返回的值将无处可寻。

async关键字告诉您函数会返回promise,并且其中可能包含功能await强大的代码。因此,由于您的代码中没有等待,因此它看起来像

function moveOneStepAsync() {
  setTimeout(() => {
    return console.log('Hello world!');
  }, 1000);
  return Promise.resolve();
}

因此,您await的主用户将等待一个事件循环跳动,转到下一个“步骤”

阅读有关setTimeout,事件循环以及希望进一步了解的内容

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章