编写承诺的异步/等待版本 [英] Writing async/await version of a promise

查看:60
本文介绍了编写承诺的异步/等待版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码按预期每秒记录一次"hello world".

The code below logs 'hello world' once in a second as expected.

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();
}

考虑async函数的return值对应于promise中resolve函数返回的内容,为什么下面的代码不输出相同的结果,而是立即记录所有的"hello world" :

Considering the return value of an async function corresponds to what is returned from resolve function in promises, why doesn't the code below output the same result, but instead logs all the 'hello world's at once:

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

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

推荐答案

这是因为setTimeout不会在您的main函数中将承诺返回给await. setTimeout本身是同步执行的.它将回叫作为参数传递给事件循环,以便在提到的时间执行.

That's because setTimeout does not return promise to await it in your main function. setTimeout itself executes synchronously. It adds to an event loop the callback that is passed as an argument to execute in time that is mentioned.

在此代码中,回调的返回也没有任何意义,因为回调将在1秒钟内运行,并且返回的值将无处获取.

Also in this code return of your callback means nothing as callback with be run in 1 sec and the returned value will go nowhere.

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

async keyword tells you that functions returns promise and could have awaitable code in it. So as there is not await in your code it then looks like

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

因此,您的主await将等待一个事件循环滴答,然后转到下一个步骤"

So your await in main will await one event loop tick to go to the next "step"

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

Read about setTimeout, event loop, and what await expects to understand it more in-depth

这篇关于编写承诺的异步/等待版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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