onMessage listerner中的异步sendResponse

时间:2017-08-26 21:48:53

标签: javascript google-chrome-extension promise

我正在构建Chrome扩展程序,其中包含后台脚本和覆盖页面脚本之间的一些通信。

background.js(后台脚本):

function deleteWord(wordTransPair) {
   // getWords returns a Promise
  return getWords().then(function(words) {
    wordsLen = words.length;
    console.log("wordsLen in cb f: ", wordsLen);
    console.log("words arr: ", words);
    for (let i = 0; i < wordsLen; i++) {
      if (
        words[i][0] === wordTransPair[0] &&
        words[i][1] === wordTransPair[1]
      ) {
        words.splice(i, 1);
        break;
      }
    }
    let updatedWords = words.length;
    chrome.storage.local.set({ fishky: words }, function() {});

    wordsLen = updatedWords;
    console.log(wordsLen);
    return wordsLen;
  });
}

deleteWord函数返回一个promise,我无法在sendResponse()内使.then()更正。 sendResponse()在.then()回调之外正常工作。

我无法找到重构代码的方法,以便sendResponse()发送数字值。

background.js中的

消息监听器:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {

  if (request.wordsToDel) {

    // delete words
    deleteWord(request.wordsToDel).then((updatedWordsLen) => {
        console.log(typeof updatedWordsLen); // number
        sendResponse({ wordsCountAfterDel: updatedWordsLen });  // here it doesn't work

    });

    sendResponse({ wordsCountAfterDel: "this response works" }); // here it works as expected 
  }
});

updateGrid.js(覆盖页面)

  function deleteItem(e) {
        var wordsToDel = [];
        wordsToDel.push(e.target.parentNode.firstChild.innerText);
        wordsToDel.push(e.target.parentNode.children[1].innerText);

        chrome.runtime.sendMessage({
            wordsToDel: wordsToDel
        }, function (response) { 

            console.log("response: ",response); // prints response: undefined in the first case, and response: { wordsCountAfterDel: "this response works" } in the call outside .then
            if (response.wordsCountAfterDel === 0) {
                renderEmptyList();
            }

        });

0 个答案:

没有答案