在同一个异步函数中使用多个setTimeout/计时器重置 [英] Using multiple setTimeout in the same async function / Timer reset

查看:228
本文介绍了在同一个异步函数中使用多个setTimeout/计时器重置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当试图理解异步/等待时,我尝试了这段代码,其行为与我期望的不一样.

When trying to understand async/await, I tried this block of code that didn't behave the way I expected it to.

let test = async function () {
  let result = new Promise((resolve, reject) => {
    setTimeout(() => resolve('done1'), 2000)
  })

  let result2 = new Promise((resolve, reject) => {

    setTimeout(() => resolve('done2'), 2500)
  })

  let x1 = await result
  console.log(x1)


  let x2 = await result2
  console.log(x2)

}

test()

我希望控制台在2秒钟后显示完成1,然后在完成1 2.5秒后显示完成2.相反,它在2秒内显示done1,然后在0.5秒后显示done2.为什么在显示第一个setTimeout之后等待第二个setTimeout,所以它为什么会如此?

I was expecting the console to display done1 after 2seconds, then display done2 2.5 seconds after done1. Instead, It displayed done1 in 2seconds and done2 0.5seconds after that. Why does it behave like this, since I await the second setTimeout after displaying the first one?

推荐答案

创建new Promise时,它开始运行其代码.当其中包含setTimeout时,实际上计时器正在运行.当您在Promise调用之前使用await时,它将等待,直到诺言将被解决或被拒绝,然后工作.

When you create a new Promise, it starts to run it's code. When you have setTimeout inside it, actually the timer is going. When you use await before the Promise call, it waits until the promise will be resolved or rejected and then work.

您需要创建每个承诺,然后等待.

You need to create each promise and after that wait for it.

let test = async function () {

  let result = new Promise((resolve, reject) => {
    setTimeout(() => resolve('done1'), 2000);
  });
  
  let x1 = await result;
  console.log(x1);

  let result2 = new Promise((resolve, reject) => {
    setTimeout(() => resolve('done2'), 2500);
  });

  let x2 = await result2;
  console.log(x2);

}

test()

这篇关于在同一个异步函数中使用多个setTimeout/计时器重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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