Chrome 扩展同步调用 - 仅在窗口关闭后创建窗口

bhc*_*c11 2 javascript asynchronous google-chrome-extension promise


我有这个代码:

function voteNewWindow(mailNum) {
    chrome.windows.create({
        url: 'http://www.google.com',
        incognito: true
    }, function (window) {
        console.log('created ' + window.id);
        chrome.tabs.query({
            active: true,
            windowId: window.id
        }, function (tabs) {
            var tab = tabs[0];
            chrome.tabs.executeScript(tab.id, {
                file: "jquery-2.1.1.min.js"
            }, function () {
                chrome.tabs.executeScript(tab.id, {
                    file: "content_script.js"
                }, function () {
                    chrome.tabs.sendMessage(tab.id, {
                        email: JSON.parse(localStorage.mailList)[mailNum]
                    }, function (response) {
                        console.log(response);
                        chrome.windows.remove(window.id);
                        console.log('window ' + window.id + " removed");
                    });
                });

            });
        });

    });
}


function execute() {

    for (var i = 0; i < JSON.parse(localStorage.mailList).length; i++) {

        voteNewWindow(i);
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是所有窗口同时打开。我希望只有当前面的窗口关闭时才打开一个窗口。我希望 voteNewWindow() 在另一个 voteNewWindow() 执行之前完成它必须做的所有事情。
任何帮助,将不胜感激。谢谢

Xan*_*Xan 5

JavaScript Promise来拯救你!

function voteNewWindow(mailNum) {
  return function(){
    return new Promise( function (resolve, reject){
      chrome.windows.create({
      /* ... */
                        }, function (response) {
                            console.log(response);
                            chrome.windows.remove(response.id);
                            console.log('window ' + response.id + " removed");
                            resolve(); // Proceed to the next
                        });
      /* ... */
    }
  }
}

function execute() {
  var sequence = Promise.resolve();
  for (var i = 0; i < JSON.parse(localStorage.mailList).length; i++) {
    sequence = sequence.then(voteNewWindow(i));
  }
}
Run Code Online (Sandbox Code Playgroud)

请参阅本节以了解此处发生的情况。基本上,我们正在创建一系列由 粘合在一起的 Promise then,这确保下一个 Promise 仅在前一个 Promise 完成后才开始执行。

如果您需要在 后执行任何其他操作execute(),请将其放在序列的末尾:

function execute(callback) {
  var sequence = Promise.resolve();
  for (var i = 0; i < JSON.parse(localStorage.mailList).length; i++) {
    sequence = sequence.then(voteNewWindow(i));
  }
  sequence.then(callback);
}
Run Code Online (Sandbox Code Playgroud)