2012-10-21 66 views
3

我被困在這個異步函數問題上。我需要使用從回調函數獲得的數據設置全局變量。我怎樣才能做到這一點?如何從異步函數設置全局變量

var soundId; 

soundcheck(soundId, function (num){getSound(soundId, num)}); 
//callback 
function getSound (soundId, result) { 
var res = result; 
if (!soundId) { 
    soundId = res; 
    } 
    console.log(soundId); 
}; 


function soundcheck(soundId, callback) { 
    var lpid = $("a#entered_user_link").attr('href').substring(6); 
     chrome.extension.sendMessage({lpid: lpid}, function(response) { 
     if (response.resp) { 
      check = response.resp; 
      callback(check); 
     } 
    }); 
}; 

// i need to put response in this variable to use it in future 
console.log(soundId); 

回答

3

您可能希望保持簡單,特別是不要隱藏變量。

var soundId; 

soundCheck(function(result) { 
    if(result) { 
    soundId = result; 
    }; 
}); 

var soundCheck = function(callback) { 
    var lpid = $("a#entered_user_link").attr('href').substring(6); 
    chrome.extension.sendMessage({lpid: lpid}, function(response) { 
    callback(response.resp); 
    }); 
}; 

沒有理由畢竟以繞過soundId

+0

很多!得到了我的錯誤)) – user1330964

+0

@ user1330964,好吧,別忘了標記你的答案:) – Alexander