简体   繁体   English

有没有办法自定义promise.all?

[英]Is there any way to customise promise.all?

As per the current behavior, The Promise.all() method returns a single Promise that resolves when all of the promises passed as an iterable have resolved or when the iterable contains no promises.根据当前行为, Promise.all() 方法返回一个 Promise,当所有作为可迭代传递的承诺都已解决或可迭代不包含承诺时,该 Promise 会解决。 It rejects with the reason for the first promise that rejects.它以第一个拒绝的承诺的原因拒绝。

For example:例如:

var promise1 = Promise.resolve(3);
var promise2 = 42;
var promise3 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
});
// expected output: Array [3, 42, "foo"]

Currently, I was trying to implement a polyfill something similar to promise.all (Like, promise.sequenceAll ) where the result of the 1st promise will be fed to the next promise.目前,我试图实现类似的填充工具的东西promise.all (喜欢promise.sequenceAll其中第一承诺的结果将被送到下一个诺言)。

var promise1 = Promise.resolve(3);
var promise2 = 42;
var promise3 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 100, 'foo');
});

Promise.sequenceAll([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
});

Expected output: The result of promise1 will be passed to the promise2 as an argument.预期输出:promise1 的结果将作为参数传递给 promise2。 If any of the promises rejects, then it will execute promise.catch();如果任何一个 promise 被拒绝,那么它将执行promise.catch();

You can just do this and return the resolved value of the first promise from a .then() handler which will make it become the resolved value of the resulting promise: 您可以执行此操作,并从.then()处理程序返回第一个承诺的已解决值,这将使它成为最终承诺的已解决值:

Promise.all([promise1, promise2, promise3]).then(([v1]) => {
   // make the resolved value of the first promise be the resolved value
   // of the subsequent promise
   return v1;
}).then((value) => {
   // v1 is now the resolved value of the chain
   console.log(value);
});

You could encapsulate that behavior in your own function is you wanted, though it's pretty easy to just add a .then() handler onto an existing Promise.all() when you want this behavior. 你可以封装在自己的函数行为是你想要的,但它是很容易只需添加一个.then()处理程序到现有Promise.all()当你想这种行为。

Seems that promise.pipe is exactly what you need 似乎promise.pipe正是您所需要的

https://www.npmjs.com/package/promise.pip https://www.npmjs.com/package/promise.pip

Sadly, I don't have an ability to check right now but it seems possible using Array.reduce(), take a look at this article: https://css-tricks.com/why-using-reduce-to-sequentially-resolve-promises-works/ They were able to at least sequentially execute them. 不幸的是,我现在没有能力检查,但是似乎可以使用Array.reduce()来看看这篇文章: https : //css-tricks.com/why-using-reduce-to-sequentially -resolve-promises-works /他们至少能够顺序执行它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM