javascript 顺序承诺

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 顺序承诺相关的知识,希望对你有一定的参考价值。

// The code below executes a list of promises sequentially, so that the next request is only submitted
// after the previous one resolved. It returns a list with all the promise responses, in the same order
const sequentialPromises = promiseFactories => promiseFactories.reduce((acc, promiseFactory) => {
  return acc.then((accumList) => {
    return promiseFactory()
      .then((serverResponse) => 
        serverResponse.ok 
        ? serverResponse.json() 
        : Promise.resolve({ error_code: 'SERVER_ERROR' })
      )
      .then((jsonResponse) => accumList.concat(jsonResponse));
  });
}, Promise.resolve([]));

// HOW TO USE IT

const bookRoomsSequentially = (sessionKey, availState) => {
  const requests = buildRoomRequests(sessionKey, availState);
  const requestPromiseFactory = request => () => APIPost('/booking/basket/add/room/', request);
  return sequentialPromises(requests.map(requestPromiseFactory));
};


以上是关于javascript 顺序承诺的主要内容,如果未能解决你的问题,请参考以下文章

返回promises的Javascript顺序函数

复杂承诺返回链中的承诺 catch() 顺序

如何按顺序执行承诺并返回所有结果[重复]

如何按顺序执行一系列承诺?

承诺按顺序运行嵌套承诺并在第一次拒绝时解决

通过 jQuery addClass 调用使用标准 JS 承诺