0

我正在尝试使用 JavaScript 承诺,以便我的其余代码等待我的异步 'chrome.storage.local.get' 调用。但是,代码似乎仍在异步运行,因此会发送未定义的数据。

JavaScript 代码:

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

    if( request.message === "fetch-local-storage" ){//if popup request local data

        var responseData;

        let store = new Promise(function(resolve, reject){
            chrome.storage.local.get('localSearchList', function(query){
                responseData = query.localSearchList;
                resolve(responseData); // <- pass responseData to then()
            }); //fetch the local storage data 
        });

        store.then(function(responseData){ // <= response data will be avaialble in then, executing ONLY after the asych get call is executed
            sendResponse({message: "local-storage-data", data: JSON.stringify(responseData)});
        });

    }
 }

控制台显示以下输出:

The data being sent to popup (via content.js pipeline): undefined
asynch data: "[{\"word\":\"mo\",\"color\":\"rgb(128,0,128)\",\"id\":\"0\"}]"

如果你回头看代码,这个显示表明它没有同步工作......

4

2 回答 2

1

您需要resolve在回调中调用。关键resolve是,一旦异步操作完成,它就会被调用,而你知道的唯一方法是在回调触发时。

此外,您不应该依赖外部变量responseData,您应该将此信息传递到您的解析函数中,该函数可用于then()

let store = new Promise(function(resolve, reject){
    chrome.storage.local.get('localSearchList', function(query){
        responseData = query.localSearchList;
        console.log("asynch data: " + JSON.stringify(responseData));
        resolve(responseData); // <- pass responseData to then()
    }); //fetch the local storage data 
});

store.then(function(responseData){ // <= response data will be avaialble in then
    console.log("The data being sent to popup (via content.js pipeline): " + JSON.stringify(responseData));
    sendResponse({message: "local-storage-data", data: JSON.stringify(responseData)});
});

这将解决问题,但是当您只是要调用它时,在这里创建一个承诺有点过头了then()。为什么不将所有内容都放在回调中并省去麻烦呢?

  chrome.storage.local.get('localSearchList', function(query){
        responseData = query.localSearchList;
        console.log("The data being sent to popup (via content.js pipeline): " + JSON.stringify(responseData));
        sendResponse({message: "local-storage-data", data: JSON.stringify(responseData)});
        }); 

}

于 2018-05-23T05:45:41.220 回答
-1

有同样的问题,参考这里的代码

如果我没有错,您需要使用 async 并等待,但在我的情况下,即使这样也没有成功,所以在状态变量上使用它以正确工作/在页面回发(我认为它进入事件循环并等待直到堆栈为空以从 fetch.then 返回数据)

于 2018-05-23T05:42:00.537 回答