简体   繁体   中英

Javascript promises not acting synchronously

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)});
        }); 

}

had the same issue , refer codes from this

You need to make use of async and await if i am not wrong , but in my case even that did not work out , so used it on state variable to correctly work / on page post back(I think it gets onto event loop and wait till the stack is empty to return back the data from fetch.then )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM