In the below pseudocode, when the for loop executes each iteration, then will the for
loop block at each iteration waiting for the response of the async fetch
(because await
is used within the myasyncfn
? Or do I need to use await
keyword as shown in the comment below?
async myasyncfn(url){
return await fetch(url..).response;
}
for each url in url_array:
myasyncfn(url); #await myasyncfn(url)
CodePudding user response:
It will not wait for the async
function to complete before continuing the loop; in that sense, it will block. However, that just means it iterates through all URLs in quick succession, firing many fetch
requests, which will then all run in the background in parallel. Once the loop is done firing those, your thread is unblocked.
To illustrate:
async function foo(i) {
await new Promise(resolve => setTimeout(resolve, 5000));
console.log('Completed', i);
}
for (let i = 0; i < 10; i ) {
foo(i);
console.log('Fired', i);
}
console.log('Done firing all async functions, unblocking...');