Promise数组一旦完成就解决Promise?

时间:2017-07-13 23:27:42

标签: javascript promise

我有一系列Promise,我想在完成后立即触发某些操作。 Promises.all并不是我想要的,因为等待Promises中的所有Iterable都已完成。 Promises.race返回完成返回的第一个Promise。

假设您只能使用:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

2 个答案:

答案 0 :(得分:2)

考虑到你想要使用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

答案 1 :(得分:0)

您可以创建一个方法promiseSerial,它将按顺序而不是并行地解析承诺。

以下是一个示例实现:

/*
* 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)

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