我正在尝试使用 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\"}]"
如果你回头看代码,这个显示表明它没有同步工作......