Javascript 承诺不同步

Javascript promises not acting synchronously

我正在尝试使用 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\"}]"

如果你回头看看代码,这个显示表明它没有同步工作...

有同样的问题,参考代码来自this

如果我没记错的话,你需要使用 async 和 await ,但在我的情况下,即使那样也行不通,所以在状态变量上使用它以正确工作/在第 post 页返回(我认为它进入事件循环并等到堆栈为空以 return 从 fetch.then )

返回数据

您需要在回调中调用resolveresolve 的要点是,一旦异步操作完成,它就会被调用,而你知道的唯一方法是回调触发时。

此外,您不应该依赖于外部变量 responseData 您应该将此信息传递到您的解析函数中,以便 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() 时在这里创建一个 promise 有点矫枉过正。为什么不把所有东西都放在回调中,省去麻烦?

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

}