[英]Javascript promises not acting synchronously
我正在嘗試使用JavaScript Promise,以便我的其余代碼等待我的異步“ 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\"}]"
如果您回頭看代碼,此顯示將顯示它無法同步工作...
您需要在回調中調用resolve
。 resolve
的要點是,一旦異步操作完成,就將調用此方法,並且您知道的唯一方法是觸發回調時。
另外,您不應該依賴於外部變量responseData
,而應將此信息傳遞到resolve函數中,該函數可用於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()
在此處創建一個承諾是一種矯kill過正。 為什么不將所有內容都放在回調中,從而省去麻煩呢?
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)});
});
}
有同樣的問題,請參考此代碼
如果我沒有記錯的話,您需要使用async並等待,但是就我而言,即使這樣也無法解決問題,因此請在狀態變量上使用它來正確地工作/頁面回發(我認為它進入了事件循環並等待直到堆棧為空以從fetch.then返回數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.