Promise.all 和. 有什么区别? x => Promise.all(x) 在承诺链中?
What is the difference between Promise.all vs. x => Promise.all(x) in a promise chain?
我一直在尝试获得一系列同时解决所有问题的承诺。我知道 Promise.prototype.then() 接受一个接受解析值的回调:
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 并将其用作回调函数?为什么我必须 'manually' 调用它?
Promise.all
期望用 Promise
* 作为 this
对象调用。这会起作用(但比箭头函数更冗长):
Promise.resolve([two, three])
.then(Promise.all.bind(Promise))
.then(console.log)
* 从技术上讲,这是指定的 here;它可以在许多方面类似于 Promise
的另一个构造函数上调用,但实际上你会想使用 Promise
本身。
我可能遗漏了一些东西,但这不是你想要完成的吗:
const one = Promise.resolve(1);
const two = Promise.resolve(2);
const three = Promise.resolve(3);
Promise.all([one,two,three]).then(console.log);
我一直在尝试获得一系列同时解决所有问题的承诺。我知道 Promise.prototype.then() 接受一个接受解析值的回调:
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 并将其用作回调函数?为什么我必须 'manually' 调用它?
Promise.all
期望用 Promise
* 作为 this
对象调用。这会起作用(但比箭头函数更冗长):
Promise.resolve([two, three])
.then(Promise.all.bind(Promise))
.then(console.log)
* 从技术上讲,这是指定的 here;它可以在许多方面类似于 Promise
的另一个构造函数上调用,但实际上你会想使用 Promise
本身。
我可能遗漏了一些东西,但这不是你想要完成的吗:
const one = Promise.resolve(1);
const two = Promise.resolve(2);
const three = Promise.resolve(3);
Promise.all([one,two,three]).then(console.log);