what I struggled with in the past, and am struggling with today, does not allow the API / AJAX to continue until you get a response. I am currently working with the Facebook API. I need to get the response from the call and then return it, but what happens is that my function returns before I receive the response from the API call. I know why this is happening, I just can't figure out how to prevent this! Here is my code ...
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; }
// ----- EDIT
I noticed that some people suggested something like this ...
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; } }); }
But this returns undefined
// EDIT ON THE BASIS OF UPDATE
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); }
source share