[英]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.