【问题标题】:Sequential Promise顺序承诺
【发布时间】:2021-02-28 08:35:48
【问题描述】:

所以我试图在不使用异步的情况下按顺序执行我的承诺,下面是我的代码

//promises is an array of function who return a promise
const p = function(promises){
    let result = promises.reduce((prevPromise, promise) => {
        return prevPromise.then(res => {
            return promise.then(Array.prototype.concat.bind(res))
        })
    }, Promise.resolve([]));
    return result;
}

现在说 promises 数组有 2 个函数,分别在 5 秒和 10 秒内执行,上面的代码在 10 秒内给出答案,但如果真正的序列执行应该在 15 秒内给出。请提出建议。

【问题讨论】:

  • async/await 有什么问题?
  • 如果你已经有一个promise数组,你唯一能做的就是等待它们(使用Promise.all)。如果你想让事情按顺序执行,这意味着你需要函数,你可以按顺序调用

标签: javascript ecmascript-6 es6-promise request-promise


【解决方案1】:

在我看来。 promises.reduce 只是链接了承诺,但没有延迟执行时间。

承诺执行时间是你创建new Promise()的时候

在您的 then 声明中创建新的承诺。

【讨论】:

  • 有很多理由不要不必要地使用 Promise 构造函数,但我怀疑性能影响是否显着
【解决方案2】:

这是因为您正在减少一组承诺,而不是执行返回承诺的异步操作。

以下面的示例为例,我们有一个返回承诺的delay() 函数,执行异步setTimeout() 操作,它解决了超时后的ms 延迟。

// a function that returns a promise that will only resolve
// after the setTimeout has finished.
const delay = ms => new Promise(resolve => setTimeout(
  resolve,
  ms,
  ms
));

// array of milliseconds to execute the delay() function
const items = [5000, 10000];

// timer to track the amount of time 
// passed after all delays are executed
console.time('delay');

// Reducing all promises wherein items are the delayed timeout
// while also the items that will be added in this reduction
const promise = items.reduce((promise, value) =>
  // wait for promise to resolve
  promise.then(result => 
    // perform async operation
    delay(value)
      // add each resolved value
      .then(item => result + item)
  ),
  // default value of reduction
  Promise.resolve(0)
);

promise.then(result => {
  // Should be the summation of the items array
  console.log('result', result);
  // show the time tracker if all of these operations
  // really finished appropriately.
  console.timeEnd('delay');
});

【讨论】:

    猜你喜欢
    • 2017-08-18
    • 1970-01-01
    • 2016-11-10
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 2019-06-16
    • 2020-06-16
    相关资源
    最近更新 更多