我的异步方法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!!!!!")
有人可以帮助我了解我在这里做错了吗!
答案 0 :(得分:4)
这里有很多错误:
for
循环必须为for (let i = 0; i < fruitsToGet.length; i++) {
,因此您都需要声明循环变量并将其在正确的位置递增。i
,而不是index
。test().then(result => console.log(result))
来知道test()
的实际完成时间,因为它是一个async
函数,因此它返回一个您必须使用.then()
进行监视的承诺。或await
知道何时完成。sleep()
的代码。 看看这个固定的代码,您可以在此代码段中运行该代码,亲自查看结果:
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!!!!!")
});
运行它时,它将生成以下输出:
start
inside test
start loop invocation 0
iside
27
start loop invocation 1
iside
0
start loop invocation 2
iside
14
done
end!!!!!