编写async/await版本的promise

Uğu*_*aya 2 javascript async-await

下面的代码按预期在一秒内记录"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();
}
Run Code Online (Sandbox Code Playgroud)

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

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

async function main() {
  await moveOneStepAsync();
  await moveOneStepAsync();
  await moveOneStepAsync();
  await moveOneStepAsync();
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*udz 6

那是因为在你的函数setTimeout中没有返回await对它的承诺main.setTimeout本身同步执行.它向事件循环添加了作为参数传递的回调,以便及时执行.

同样在这段代码中,回调意味着没有任何回调可以在1秒内运行,并且返回的值将无处可去.

async关键字告诉您函数返回promise并且可以await在其中包含代码.因此,在您的代码中没有等待它看起来像

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

所以你await的主要将等待一个事件循环勾选到下一个"步骤"

阅读有关setTimeout,事件循环以及await期望更深入理解的内容