为什么 Promise.all() 不能与异步函数一起使用?

Ae *_*ung 0 javascript es6-promise

我正在探索 Promise.all() 的使用,但我不知道为什么它没有给我预期的结果。我尝试一步一步地说明它。

让我们看一下我的代码:

var p2 = 1337;
var p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 2000, 'foo');
});


var apiCall = async () =>{
    // to simulate a api call that will response after 5 sec 
     setTimeout(() => {return 1000}, 5000); 
    
}

Promise.all([p2,p3,apiCall()]).then(values => {
  console.log(values); // [3, 1337, undefine], but I expect  [3, 1337, 1000]
});

apiCall().then((response)=>{console.log(response)})
Run Code Online (Sandbox Code Playgroud)

据我了解,async 函数会立即返回一个 Promise,这就是 Promise.all 会等待的。

所以我期望,

.then(values => {
  console.log(values); // [3, 1337, undefined]
});
Run Code Online (Sandbox Code Playgroud)

5秒后才会执行。

但 2 秒后的输出已经如下所示,而不是 [3, 1337, 1000]

undefined   
[ 1337, 'foo', undefined ]
Run Code Online (Sandbox Code Playgroud)

我不知道问题出在哪里,我预计

apiCall().then((response)=>{console.log(response)})
Run Code Online (Sandbox Code Playgroud)

会给我“1000”而不是未定义


新编辑

在收集了你们的答案后,我尝试了这个。

据我了解,setTimeout也是一个异步,它会像其他承诺一样自动返回一个承诺。

所以,基于这个理解,我写了下面的代码。但它不起作用。我知道使用 Promise 构造函数可以解决问题。但我不知道这个例子有什么问题

var apiCall = async () =>{
    // to simulate a api call that will response after 5 sec 
     const a = setTimeout(() => {return 1000}, 5000); 
    return a 
}
Run Code Online (Sandbox Code Playgroud)

Xid*_*uzo 6

您的 api 调用未正确返回值。尝试返回一个在超时后解决的承诺

var apiCall = async () =>{
  // to simulate a api call that will response after 5 sec 
  return new Promise(resolve => {
    setTimeout(() => {resolve(1000)}, 5000); 
  });
}
Run Code Online (Sandbox Code Playgroud)