为什么输出结果不同?

v g*_*eat 7 javascript

async function fn1() {
  return 1
}
async function fn2() {
  return Promise.resolve(1)
}

function fn3() {
  return Promise.resolve(1)
}

function fn4() {
  return Promise.resolve(Promise.resolve(1))
}
console.log(fn1()); //Promise {<fulfilled>: 1}
console.log(fn2()); // Promise {<pending>}
console.log(fn3()); // Promise {<fulfilled>: 1}
console.log(fn4()); // Promise {<fulfilled>: 1}
Run Code Online (Sandbox Code Playgroud)

当我运行 fn2() 时,它输出Promise { pending }.

为什么是 fn2()Promise { pending }而不是Promise {fulfilled: 1}?

Ste*_*ins 0

fn2()有点欺骗性。从函数返回 Promise 会async导致代码在尝试解析之前必须进行awaited 或then()ed 处理。 这是理解原因的起点。

编辑:这是不正确的。请参阅下面@VLAZ 的评论。