简体   繁体   English

一系列承诺会在完成后立即解决承诺吗?

[英]Array of Promises resolve Promises as soon as completed?

I have an array of Promises, and I want to trigger certain actions on them as soon as they complete. 我有一系列的Promises,我想在它们完成后立即触发某些操作。 Promises.all isn't quite what I'm looking for since it waits until all Promises in the Iterable have completed. Promises.all不是我要找的东西,因为它要等到Iterable所有Promises完成为止。 Promises.race returns whatever the first Promise which complete returns. Promises.race将返回完成的第一个Promise。

Assume that you can only use: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise 假设您只能使用: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Taking into account you want to use Vanilla JS, if you want they to execute them concurrently and as soon as they are resolved you could do something like this: 考虑到您想使用Vanilla JS,如果您希望它们同时执行它们,并且一旦解决它们,您可以执行以下操作:

// create a Promise that is resolved after passed millisecs with millisecs * 2 as value
const createP = (ms) => new Promise(resolve => setTimeout(() => resolve(ms * 2), ms));

// your array of Promises
const pArray = [createP(1000), createP(200), createP(500)];

// map() and Promise.all() is necessary in order to wait until all the promises are executed
Promise.all(pArray.map(promise => { 
  // log each result
  return promise.then(console.log);
}))
.catch(err =>{
  // do some error handling here if necessary
});

// it should log 400, 1000, 2000 in this order

You can create a method promiseSerial that will resolve promises sequentially instead of in parallel. 您可以创建一个方法promiseSerial ,该方法promiseSerial顺序而不是并行地解决promise。

Here's an example implementation: 这是一个示例实现:

/*
* promiseSerial resolves Promises sequentially.
* @example
* const urls = ['/url1', '/url2', '/url3']
* const funcs = urls.map(url => () => $.ajax(url))
*
* promiseSerial(funcs)
*   .then(console.log)
*   .catch(console.error)
*/
const promiseSerial = funcs =>
  funcs.reduce((promise, func) =>
    promise.then(result => func().then(Array.prototype.concat.bind(result))),
    Promise.resolve([]))

// some url's to resolve
const urls = ['/url1', '/url2', '/url3']

// convert each url to a function that returns a promise
const funcs = urls.map(url => () => $.ajax(url))

// execute Promises in serial
promiseSerial(funcs)
  .then(console.log)
  .catch(console.error)

from: https://hackernoon.com/functional-javascript-resolving-promises-sequentially-7aac18c4431e 来自: https : //hackernoon.com/functional-javascript-resolving-promises-sequentially-7aac18c4431e

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

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