Consider this code:
async function load() {
const data = await new Promise(resolve => {
setTimeout(() => resolve([1, 2, 3]), 10);
}).then(data => data.map(i => i * 10));
console.log(`Data inside the function: ${JSON.stringify(data)}`);
return data;
}
function main() {
const data = load();
console.log(`Loaded data: ${JSON.stringify(data)}`);
}
main();
This is the output I'm getting:
Loaded data: {}
Data inside the function: [10,20,30]
But if I change the code to this:
async function load() {
const data = await new Promise(resolve => {
setTimeout(() => resolve([1, 2, 3]), 10);
}).then(data => data.map(i => i * 10));
console.log(`Data inside the function: ${JSON.stringify(data)}`);
return data;
}
async function main() {
const data = await load();
console.log(`Loaded data: ${JSON.stringify(data)}`);
}
main();
I'll get this:
Data inside the function: [10,20,30]
Loaded data: [10,20,30]
I'm confused because based on the documentation, await
should pause the execution till the promise is resolved. In which case, the first example should return data
as an array. But as you can see, it's returning a Promise
and I have no idea why?!
At the same time, the documentation has this part which I don't understand what it is talking about:
An await can split execution flow, allowing the caller of the await's
function to resume execution before the deferred continuation of the
await's function. After the await defers the continuation of its
function, if this is the first await executed by the function,
immediate execution also continues by returning to the function's
caller a pending Promise for the completion of the await's function
and resuming execution of that caller.
It seems to me the await
is working only if all of the functions in your code are async
which is ridiculous since if I'm using a function from another module, how should I know if it's an async
or not!? Or maybe I should take the cautious side and always call all the functions with an await
regardless of whether they are async
or not!!!
[UPDATE]
Thanks to everyone participating and providing me with insight. But I'm still confused how should I be using await
and async
. Should I always call all of my function with an await
?
Let's say I'm writing a code composed of multiple functions within multiple files. If I end up using a library which returns a Promise
or it's an async
function, should I trace back all my function calls from the asynchronous point to the entry point of the application and add an await
before all the function calls after making them async
? Or maybe I should just get into the habit of calling all my functions with an await
regardless of whether they are async
or not?