2

我觉得很愚蠢,因为我已经尝试访问这个响应变量一段时间了,我想我对闭包或范围的理解不够好,所以请帮忙。

我正在开发 chrome 扩展,我正在从 contentscript.js 向 background.js 发送一条消息并接收响应。现在我想返回响应并能够在 contentscript.js 中使用它。似乎你应该能够做的事情......

function getWords(){

    var words = [];

    chrome.runtime.sendMessage({detail: "words"}, function(response) {
        console.log(response) // prints ["word1, "word2" ..]
        words = response;
    });

 return words; // = []
}

更新:谢谢,我明白我现在的问题是什么,但仍然需要一些建议来解决它。我的问题是,如果我立即需要它作为另一个函数中的参数,那么“询问”背景页面以获取单词列表的最佳方式是什么。我可以等待信息回来吗?我应该简单地从回调中调用其他函数吗?还是有其他方法?理想情况下,我想实际实现一个在列表返回之前不会返回的 getWords() ......不可能吗?我也对开源库持开放态度。

4

1 回答 1

5

因为sendMessage是异步调用,您将其视为同步调用。您正在尝试在实际拨打电话之前阅读单词。没有办法等待它。您需要使用回调。

function getWords( callback ){

    var words = [];

    chrome.runtime.sendMessage({detail: "words"}, function(response) {
        console.log(response) // prints ["word1, "word2" ..]
        callback(response);
    });

}



function processWords(words){
    //do your logic in here
    console.log(words);
}
getWords(processWords);
于 2013-07-10T14:58:16.750 回答