顺序承诺

时间:2021-02-28 08:35:48

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

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

//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 秒内给出。请提出建议。

2 个答案:

答案 0 :(得分:0)

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

承诺执行时间是您创建 new Promise()

在您的 then 语句中创建新的承诺。

答案 1 :(得分:0)

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

以下面的例子为例,我们有一个 delay() 函数返回一个 promise,执行异步 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');
});