简体   繁体   中英

how to use await/async in for loop

Why the code print this way??

await can not be used under loop?

>>>>> START
1

The expect result is '>>>>> 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. 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):

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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