I am attempting to use JavaScript promises so that the rest of my code waits for my asynchronous 'chrome.storage.local.get' call. However, it seems that the code is still acting asynchronously, and as a result sending undefined data out.
JavaScript code:
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 console shows the following output:
The data being sent to popup (via content.js pipeline): undefined
asynch data: "[{\"word\":\"mo\",\"color\":\"rgb(128,0,128)\",\"id\":\"0\"}]"
If you look back at the code, this display shows that it is not working synchronously...
You need to call resolve
in the callback. The point of resolve
is that it is called once the async operation is complete and the only way you know that is when the callback fires.
Additionally, you shouldn't be depending on an outside variable responseData
you should pass this information into your resolve function where it will be available to 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)});
});
This will fix the issue, but it's kind of overkill to create a promise here when you are just going to call then()
on it. Why not put everything in the callback and save yourself the trouble?
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)});
});
}