【问题标题】:Array of Promises resolve Promises as soon as completed?Promise 数组在完成后立即解决 Promise?
【发布时间】:2017-07-13 23:27:41
【问题描述】:

我有一组 Promise,我想在它们完成后立即触发它们的某些操作。 Promises.all 并不是我想要的,因为它会等到 Iterable 中的所有 Promises 完成。 Promises.race 返回完成返回的第一个 Promise。

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

【问题讨论】:

  • promises.forEach(p => p.then(doStuff))
  • 你能发布一个代码示例吗?根据您创建 Promise 的方式,您通常可以在各个 Promise 中使用 .then() 并使用 Promise.all 解析数组。
  • @4castle 这样做时不要忘记.catch() 错误。或者更好的是,不要使用forEach,而是使用map 并对结果做一些事情(包括错误处理)
  • @Bergi 他们仍然可以使用forEach。下一行可能是Promise.all(promises).catch(handleIt)
  • @4castle 不,他们不能,当promises 被拒绝时,这将导致thenforEach 中创建的承诺未处理的承诺拒绝

标签: javascript promise


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以创建一个方法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

    【讨论】:

    • 这是串行的,我认为他要求的是并发解决方案。
    猜你喜欢
    • 2022-10-05
    • 2020-01-11
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    相关资源
    最近更新 更多