My async method getNumFruit
is not getting called for my below code
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:
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.i
, not index
in your loop.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.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!!!!!
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.