Consider a scenario such as this :
function method1(): Promise<string> {
return new Promise((resolve, reject) => {
// do something
const response = true;
setTimeout(() => {
if (response) {
resolve("success");
} else {
reject("error");
}
}, 5000);
});
}
async function method2(): Promise<string> {
const result = await method1();
// do some other processing and return a different result
const result2 = result + "1";
return result2;
}
function method3(): void {
console.log("test 1");
const result = method2();
console.log("test 2");
}
method3();
I am not sure why method2()
would not wait for the result as it contains an await
. If I use await
for method2()
call in method3()
, it works :
async function method3(): Promise<string> {
console.log("test 1");
const result = await method2();
console.log("test 2");
}
I can't really wrap my head around how the await/async work even after reading so many blog posts, Mozilla documentation and stackoverflow answers.
One of the comments said "you can't escape asynchrony". And further explained that as any async function would be returning a promise, have to await
them all up the function ladder.
Hope someone can clarify this for me. Thank you.