Javascript承诺不会同步行事

时间:2018-05-23 05:35:16

标签: javascript asynchronous google-chrome-extension es6-promise google-chrome-storage

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

如果你回头查看代码,这个显示会显示它不能同步工作......

2 个答案:

答案 0 :(得分:0)

您需要在回调中调用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()时,在此处创建承诺有点过分。为什么不把所有内容都放在回调中并省去麻烦?

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

}

答案 1 :(得分:-1)

有同样的问题,请参考this

中的代码

如果我没有错,你需要使用异步并等待,但在我的情况下即使没有用,所以在状态变量上使用它来正确地工作/在页面上回发(我认为它进入事件循环并等待堆栈为空以从fetch.then返回数据