Really Confused About Promise Being Returned From Async Function
Solution 1:
This probably happens because the JavaScript engine needs to "flatten" the returned promise.
console.log(Promise.resolve(113)); //=> fulfilled
const a = async () => 113;
console.log(a()); //=> fulfilled
const b = async () => Promise.resolve(113);
console.log(b()); //=> pending
The last scenario logs a pending promise. This is probably because the JavaScript engine sees that you return a promise from an async function. In this scenario, when you await b()
, you expect 113
as a result. An async function always returns a promise. If the resolved value (return value of an async function) of this promise is another promise then the promise is "flattened".
To better demonstrate the point, imagine the return value of b
as (Firefox console notation):
Promise { <state>: "pending", <value>: Promse { <state>: "fulfilled", <value>: 123 } }
Whereas the return value of both the first code block and a
is:
Promse { <state>: "fulfilled", <value>: 123 }
The flattening of nested promises is done by the engine and probably added to end of the event loop and thus ran after the current running context. Which means that the outer promise is pending until that happens.
This behaviour might be engine dependant, so I would not rely on this behaviour. A Promise
instance is a promise of an eventual value and should be treated as such. Never expect a promise to resolve immediately. If you expect a fulfilled promise you are better of using a normal synchronous function, which avoids the use of promises.
Post a Comment for "Really Confused About Promise Being Returned From Async Function"