简体   繁体   English

在 for 循环中使用 async/await 不等待异步方法调用

[英]Using async/await inside for loop is not waiting for async method calls

My async method getNumFruit is not getting called for my below code我的以下代码没有调用我的异步方法getNumFruit

const fruitsToGet = ['apple', 'grape', 'pear']
const fruitBasket = {
  apple: 27, 
  grape: 0,
  pear: 14 
}
console.log("start");




async function getNumFruit(fruit) {
   console.log("iside")
  return sleep(1000).then(v => fruitBasket[fruit])
}

async function test(){
    console.log("inside test");

  for(i=0;i++;i<fruitsToGet.length){
  console.log("start2");

    const fruit = fruitsToGet[index]
    const numFruit = await getNumFruit(fruit)
    console.log(numFruit)

  }
  return "done";
}
var result = test();
console.log(result)

console.log("end!!!!!")

can someone help me understanding what I am doing wrong here!有人可以帮助我理解我在这里做错了什么!

There are lots of things wrong here:这里有很多错误:

  1. Your for loop needs to be for (let i = 0; i < fruitsToGet.length; i++) { so you both declare the loop variable and increment it in the right place.你的for循环需要是for (let i = 0; i < fruitsToGet.length; i++) {这样你就可以声明循环变量并在正确的位置增加它。
  2. Then, you need to use i , not index in your loop.然后,您需要在循环中使用i ,而不是index
  3. Then, you need to use test().then(result => console.log(result)) to know when test() is actually done because it's an async function so it returns a promise that you have to monitor with .then() or await to know when it's done.然后,您需要使用test().then(result => console.log(result))来了解test()何时实际完成,因为它是一个async函数,因此它返回一个承诺,您必须使用.then()await知道何时完成。
  4. You don't show the code for the function sleep() .您没有显示函数sleep()的代码。

Take a look at this fixed up code which you can run in this snippet to see the results for yourself:看看这个修复后的代码,你可以在这个片段中运行它来自己查看结果:

 const fruitsToGet = ['apple', 'grape', 'pear']; const fruitBasket = { apple: 27, grape: 0, pear: 14 }; console.log("start"); function sleep(t) { return new Promise(resolve => { setTimeout(resolve, t); }); } function getNumFruit(fruit) { console.log("iside") return sleep(1000).then(v => fruitBasket[fruit]); } async function test(){ console.log("inside test"); for (let i = 0; i < fruitsToGet.length; i++) { console.log("start loop invocation", i); const fruit = fruitsToGet[i]; const numFruit = await getNumFruit(fruit); console.log(numFruit); } return "done"; } test().then(result => { console.log(result); console.log("end!!!!!") });

When you run it, it generates this output:当您运行它时,它会生成以下输出:

start
inside test
start loop invocation 0
iside
27
start loop invocation 1
iside
0
start loop invocation 2
iside
14
done
end!!!!!

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

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