I attempted to run it within an async function:
There is truly no purpose to this function:
async function callPromise() {
return await goToWork;
}
It serves no real function, as it is essentially the same as:
function callPromise() {
return goToWork;
}
This function is useless and doesn't serve any meaningful purpose. It indicates a basic misunderstanding of how async/await works.
First of all, all async
functions return a promise - always. Therefore, using return await fn()
is unnecessary. You might as well use return fn()
, as both will return a promise with the same state.
I then tried awaiting callPromise like this: await callPromise() returned pending which led me to store it in another async function like so:
As mentioned before, all async
functions return a promise.
I proceeded to execute it with executePromise() // output: Go To Work
There should be no surprise here.
console.log(await callPromise());
This code will display the result of await callPromise()
, which will give you the resolved value of the promise that callPromise()
returns (if it doesn't reject).
My question is why didn't executePromise() throw an error for not being contained within an async function? Why wasn't it necessary to be "awaited"?
Here's your executePromise
function:
async function executePromise() {
console.log(await callPromise());
}
There is no issue with this function because the await
is inside an async
function, following the rules of async/await
.
When called like this:
executePromise()
It simply runs the function and since it is an async
function, it will always return a promise. There is no requirement that calling an async
function necessitates using await
or must be executed from within another async
function.
You can also call it like this:
executePromise().then(...).catch(...)
Or place it within an async
function:
async someFunction() {
try {
await executePromise();
} catch(e) {
// handle error
console.log(e);
}
}
Alternatively, you can call it without considering the returned promise:
executePromise();
Calling it without handling the promise means disregarding whether it resolves or rejects and ignoring any resolved value. This may lead to an unresolved rejection if there is no reject handler, but it is permitted if you know the promise will never reject and you are indifferent to when it resolves or what the resolved value is.