JavaScript 异步函数(或返回 Promise 的常规函数)将任何具有“then”字段函数的对象视为 Promise。那么是不是不能让这样的对象作为Promise的解析值呢?
示例:函数调用
await f()
不返回结果。如果then
的字段名称不同,则返回结果。
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();
异步函数总是返回 Promise,因此您返回的 Promise 返回带有
.then
方法的对象 - 但正确的 .then 方法需要两个参数,都是函数。 onFulfilled
和 onRejected
- 那么你的 then
函数不是一个有效的 Promise
为了让它工作,你可以这样写
async function f() {
return {
then(res, rej) {
res(42);
}
};
}
async function main() {
let result=await f();
console.log(result);
f().then(result => console.log(result));
}
main();