在我的分機的內容腳本,我從background.js請求數據,像這樣:消息回調同步誤差
fireOnNewTopic(); // Initial run on cold start or full reload.
window.addEventListener ("hashchange", fireOnNewTopic, false);
function fireOnNewTopic() {
/*-- For the pages we want, location.hash will contain values
like: "#!newtopic/{group title}"
*/
if (location.hash) {
var locHashParts = location.hash.split ('/');
if (locHashParts.length > 1 && locHashParts[0] == '#!newtopic') {
var subjectStr = '';
var bodyStr = '';
switch (locHashParts[1]) {
case 'opencomments-site-discussions':
chrome.extension.sendMessage({name:"domain"},
function(response)
{
subjectStr = response.domain;
});
chrome.extension.sendMessage({name:"url"},
function(response)
{
bodyStr = "URL of last page visited: " + response.url;
});
break;
default:
break;
}
if (subjectStr && bodyStr) {
runPayloadCode (subjectStr, bodyStr);
}
}
}
}
不幸的是,因爲的sendMessage()的回調異步運行,在代碼到達runPayloadCode(時間),因爲background.js中的代碼尚未完成,所以subjectStr和bodyStr仍爲空。什麼是同步代碼的最佳方法,以便在調用runPayloadCode()時調用subjectStr和bodyStr?
這是你在追求什麼? http://stackoverflow.com/questions/10783093/any-better-way-to-combine-multiple-callbacks –