我有这段代码:
function fetchSocialCount(type,fileSrc){
var count = {likes: 0, dislikes: 0};
var req = new XMLHttpRequest();
req.onload = function(){
if(req.status === 200 && req.readyState === 4){
var countResponse = json_encode(req.responseText);
count.likes = countResponse.likes;
count.dislikes = countResponse.dislikes;
return count;
}
}
}
所以,我想从count
函数表达式返回req.onload
,就好像它是从fetchSocialCount
函数返回的一样。我怎样才能做到这一点?
答案 0 :(得分:2)
req.onload是异步的。您需要使用回调,承诺或类似的东西来获得结果“计数”
function fetchSocialCount(type,fileSrc, cb){
var count = {likes: 0, dislikes: 0};
var req = new XMLHttpRequest();
req.onload = function(){
if(req.status === 200 && req.readyState === 4){
var countResponse = json_encode(req.responseText);
count.likes = countResponse.likes;
count.dislikes = countResponse.dislikes;
cb(count);
}
}
}
//calling fetchSocialCount
fetchSocialCount(my_type, my_file_src, function(count){
//here it is
console.log(count);
});