为什么直接将Promise.all传递给.then函数会抛出错误?

RCh*_*aud 7 javascript

我想直接传递Promise.all.then像这样的函数:

const test = [
    Promise.resolve(),
    Promise.resolve(),
    Promise.resolve(),
    Promise.resolve()
];

Promise.resolve(test) // It's supposed to be an AJAX call
.then(Promise.all) // Get an array of promises
.then(console.log('End');
Run Code Online (Sandbox Code Playgroud)

但是这段代码会引发错误Uncaught (in promise) TypeError: Promise.all called on non-object.

当我删除速记语法时,它的工作原理如下:

Promise.resolve(test)
.then(queries => Promise.all(queries))
.then(console.log('End'));
Run Code Online (Sandbox Code Playgroud)

那么为什么一个Promise.all直接传递给一个.then错误?(为什么一个console.log工作正常?)

Yur*_*nko 7

你需要绑定 Promise.all.bind(Promise)

从ES2015 规范:

all函数要求其this值为构造函数,该函数支持Promise构造函数的参数约定.

或者更好地直接在阵列上使用它.

const test = [
    Promise.resolve(1),
    Promise.resolve(2),
    Promise.resolve(3),
    Promise.resolve(4)
]

Promise.resolve(test)
  .then(Promise.all.bind(Promise))
  .then(x => console.log(x))
  
Promise.all(test)
  .then(x => console.log(x))
Run Code Online (Sandbox Code Playgroud)

  • @RChanaud我怀疑你的ajax请求神奇地回复了承诺.所以你仍然可以在`then`回调中创建一个promise数组,这样你就可以返回`Promise.all(promises)`而不是数组 (2认同)