几个then()的执行顺序链接到单个promise

时间:2017-06-23 16:47:36

标签: javascript promise

我有一个处理Chrome窗口事件的事件处理程序。为了处理这些事件,我在chrome.windows.get中调用异步promise并使用then()来处理事件。

问题是当链接到单个promise的多个then()解析时,它们的执行顺序与源事件顺序不同。例如,我得到事件1,2和3,但执行顺序可能是3,2,1。

我需要以与事件发生的顺序相同的顺序执行所有then()

简化代码示例:

chromeWinRequests = new Map();

function eventHandler(windowId) {
  if (!chromeWinRequests.has(windowId)) {
    chromeWinRequests.set(windowId, new Promise((resolve, reject) => {
       chrome.windows.get(windowId, {populate: true}, (cwin) => {
         if (!chrome.runtime.lastError) {
           resolve(cwin);
         } else {
           reject(chrome.runtime.lastError.message);
         }
       });
    }));
  }

  chromeWinRequests.get(windowId).then((cwin) => {
     // process event here
     // when I get here, the source order of events is not preserved
  });
}

我有什么办法可以保留处理顺序吗?

提前谢谢。

2 个答案:

答案 0 :(得分:0)

而不是:

chromeWinRequests.get(windowId).then((cwin) => {
    // process event here
    // when I get here, the source order of events is not preserved
});

使用Promise.all,这将确保所有以前收集的承诺在进入then回调之前已经解决。在那里,您需要获得在此上下文中创建的值的承诺值:

Promise.all(
    Array.from(chromeWinRequests, ([windowId, promise]) => promise)
).then( (cwins) => {
    const cwin = cwins.pop(); // get the promised value we're interested in
    console.log(cwin);
    // further processing....
});

答案 1 :(得分:0)

通过将最后一段代码更改为以下内容来解决问题:

newPromise = chromeWinRequests.get(windowId).then((cwin) => {
     // process event here
     return cwin;
});
chromeWinRequests.set(windowId, newPromise);

感谢Luizgrs