简体   繁体   English

如何在 for 循环中使用 await/async

[英]how to use await/async in for loop

Why the code print this way??为什么代码以这种方式打印?

await can not be used under loop?循环下不能用await吗?

>>>>> START
1

The expect result is '>>>>> START 1 2 3 >>>>> END'预期结果是'>>>>> START 1 2 3 >>>>> END'

let arr = [1, 2, 3]
async function print() {
  for (let n of arr) {
    await new Promise(
      resolve => {
        setTimeout(() => {
          console.log(n);
          resolve;
        }, 1000)
      }
    );
  }
}

async function main() {
  console.log(">>>>> START");
  await print();
  console.log(">>>>> END");
}

main()

Simple typo, you are not calling the resolve function.简单的错字,您没有调用resolve function。 You need to actually invoke it, otherwise your promise will never resolve and your code will never continue (note the addition of parentheses after resolve in your print function):您需要实际调用它,否则您的 promise 将永远无法解析,并且您的代码将永远不会继续(请注意在您的print函数中resolve后添加括号):

async function print() {
  for (let n of arr) {
    await new Promise(
      resolve => {
        setTimeout(() => {
          console.log(n);
          resolve(); // invoke the function
        }, 1000)
      }
    );
  }
}

Also, each console.log call prints on a new line so the output won't be exactly what you expect, instead it'll be more like:此外,每个console.log调用都打印在新行上,因此 output 不会完全符合您的预期,而是更像:

>>>>> START
1
2
3
>>>>> END

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM