[英]What is the difference between Promise.all vs. x => Promise.all(x) in a promise chain?
I've been trying to get an array of promises to resolve all at the same time. 我一直试图获得一系列承诺,以同时解决所有问题。 I know that Promise.prototype.then() takes a callback which accepts the resolved value:
我知道Promise.prototype.then()接受了一个接受解析值的回调:
const one = Promise.resolve(1) one.then( console.log ) // 1 one.then( x => console.log(x) ) // 1
When I try to invoke Promise.all on an array of promises, I have to use a callback to make it work. 当我尝试在Promise数组上调用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 )
What's going on here? 这里发生了什么? Why can't I just pass in Promise.all and have it work as the callback function?
为什么我不能仅传入Promise.all并将其用作回调函数? Why do I have to 'manually' call it?
为什么我必须“手动”调用它?
Promise.all
expects to be called with Promise
* as the this
object. Promise.all
期望以Promise
*作为this
对象被调用。 This would work (but be more verbose than the arrow function): 这可以工作(但比箭头功能更冗长):
Promise.resolve([two, three])
.then(Promise.all.bind(Promise))
.then(console.log)
* Technically, this is specified here ; *从技术上讲,这是在此处指定的; it can be called on another constructor that is similar to
Promise
in a number of ways, but in practice you'll want to use Promise
itself. 可以在许多方面类似于
Promise
另一个构造函数上调用它,但实际上,您将需要使用Promise
本身。
I might be missing something but isn't this what you're trying to accomplish: 我可能会缺少一些东西,但这不是您要完成的事情:
const one = Promise.resolve(1);
const two = Promise.resolve(2);
const three = Promise.resolve(3);
Promise.all([one,two,three]).then(console.log);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.