The JavaScript async function(or regular function that returns Promise) regards any object that has function with "then" field as a Promise. So is it impossible to let such object as a resolved value of Promise?
Example: The function call await f()
does not return result. If the field name of then
is different name, it returns result.
async function f() {
return {
then() {
//This function is just a function that somehow the name "then" is appropriate for.
return 42;
}
};
}
async function main() {
let result=await f();// it stops here.
console.log(result);
console.log(result.then());
}
main();
2
Answers
an async function always returns a Promise, so you’re returning a Promise that returns an object with a
.then
method – but a proper .then method takes two arguments, both functions.onFulfilled
andonRejected
– yourthen
function is not a valid Promise thenTo make it work, you’d write it something like this instead
If you read the documentation about
await
you will noticeAnd then you follow to the
thenable
docs, you will find thatand
So, the combination of
await
and returning an object with athen
method suggests to the js engine that this is a thenable object. So it expects it to have correctly implemented thethenable
interface.