Imagine a situation like this:
function process1(): Promise<string> {
return new Promise((resolve, reject) => {
// do something
const response = true;
setTimeout(() => {
if (response) {
resolve("success");
} else {
reject("error");
}
}, 5000);
});
}
async function process2(): Promise<string> {
const result = await method1();
// perform additional processing and return a different output
const result2 = result + "1";
return result2;
}
function process3(): void {
console.log("test 1");
const result = process2();
console.log("test 2");
}
process3();
I find it puzzling why process2()
doesn't wait for the result despite having an await
. Adding await
to the call of process2()
in process3()
makes it work:
async function process3(): Promise<string> {
console.log("test 1");
const result = await process2();
console.log("test 2");
}
The concept of how async/await operates is still unclear to me even after going through numerous blog posts, Mozilla documentation, and stackoverflow answers.
One of the comments mentioned that "you can't escape asynchrony". It was further explained that since any async function would return a promise, all calls must be awaited throughout the function chain.
I hope someone can shed some light on this for me. Thank you.