The answer from Jonas Wilms is absolutely correct. I just want to expand upon it with some clarification, as there are two key things one needs to understand:
Async functions are actually partially synchronous
This, I think, is the most important thing. Here is the thing - knowledge of async functions 101:
- They will execute later.
- They return a Promise.
But point one is actually wrong. Async functions will run synchronously until they encounter an await
keyword followed by a Promise, and then pause, wait until the Promise is resolved and continue:
function getValue() {
return 42;
}
async function notReallyAsync() {
console.log("-- function start --");
const result = getValue();
console.log("-- function end --");
return result;
}
console.log("- script start -");
notReallyAsync()
.then(res => console.log(res));
console.log("- script end -");
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…