2017-06-13 86 views
2

我一直在尝试获得一组承诺来同时解决所有问题。我知道Promise.prototype.then()接受它接受解析值的回调:承诺链中的Promise.all与x => Promise.all(x)有什么区别?

const one = Promise.resolve(1) 
 

 
one.then(console.log) // 1 
 
one.then(x => console.log(x)) // 1

当我尝试调用Promise.all承诺的阵列上,我不得不使用一个回调使其工作。

const two = Promise.resolve(2) 
 
const three = Promise.resolve(3) 
 

 
Promise.resolve([two, three]) 
 
    .then(xs => Promise.all(xs)) // Works 
 
    .then(console.log) // [2,3] 
 
    
 
Promise.resolve([two,three]) 
 
    .then(Promise.all) // Error 
 
    .then(console.log)

这是怎么回事吗?为什么我不能传递Promise.all并让它作为回调函数工作?为什么我必须“手动”调用它?

回答

3

Promise.all预计将被调用Promise *作为this对象。这会工作(但比箭头功能更详细):

Promise.resolve([two, three]) 
    .then(Promise.all.bind(Promise)) 
    .then(console.log) 

*从技术上讲,这是指定here;它可以通过多种方式在另一个类似于Promise的构造函数上调用,但实际上您会想要使用Promise本身。

相关问题