我过去一直在努力的事情,今天正在努力阻止API/AJAX继续,直到您收到您的回复。目前我正在使用Facebook API。我需要从一个调用得到响应然后返回它,但是发生的事情是我的函数在我从API调用得到响应之前返回。我知道为什么会发生,我无法弄清楚如何防止它!这里是我的代码...在继续之前等待API调用以Javascript完成之前
function makeCall(){
var finalresponse = "";
var body = 'Test post';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
finalresponse = response.error;
} else {
finalresponse = 'Post ID: ' + response.id;
}
});
return finalresponse;
}
// -----编辑
我注意到有些人认为这样的事情...
function makeCall(){
var finalresponse = "";
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
finalresponse = response.error;
return finalresponse;
} else {
finalresponse = 'Post ID: ' + response.id;
return finalresponse;
}
});
}
但这返回undefined
//根据更新编辑
function share_share(action_id){
var finalresponse = makeCall(action_id, process);
return finalresponse;
}
function makeCall(action_id, callback){
var body = 'Test post';
FB.api('/me/feed', 'post', { message: body }, function (response) {
if (!response || response.error) {
var finalresponse = response.error;
} else {
finalresponse = 'Post ID: ' + response.id;
}
callback(action_id, finalresponse);
});
}
function process(action_id, finalresponse){
console.log(finalresponse);
}
我相信因为你的'return finalresponse;'在API调用之外。 –
您的退货将在FB.api完成之前执行 – Dhiraj
您在编辑中提供的代码不正确。在回调中返回finalResponse将返回给您的回复回调的调用者。未定义的原因返回给makeCall()的调用者是因为make call没有返回任何东西。 –