Im sorry for the question since there are already many similar questions. However, I still dont understand. The code below is suppose to show HOW to make a for loop act synchronous. However, as I see it its still not snychronous. The output of the code below is ** 1 2 3 after forEach done **
But I wonder, if we put the await keyword in front of the function, why is the output not:
** 1 after forEach 2 after forEach 3 after forEach done **
? Because result holds one num at a time, waiting for the execution of returnNum.
const asyncFunction = async () => {
const nums = [1, 2, 3];
for (const num of nums) {
const result = await returnAsyncNum(num);
console.log(result);
}
console.log('after forEach');
}
const returnAsyncNum = x => {
return new Promise(resolve => setTimeout(resolve, 500, x));
}
asyncFunction().then(() => {
console.log('done');
})
The console.log('after forEach') will only execute once the for is fully completed. That does makes sense since you are letting it after the for of, doesn't it?
If you put a console.log before the resolve(x), you will see how the code is waiting for the promise to return the number.
That's point of async functions, they allow you to write async code as if it were sync.
You are waiting for the promise to complete and get its value.
Since you are waiting for the Promise, the execution of the async function stops in the await and when the Promise fulfills you get its value and the execution continues.
Also your expected output does not make any sense, console.log('after forEach') can only log once by calling the function once.