Waiting for an asynchronous result

I'm sick of the following problem:

I am requesting the Facebook API for some permissions using the facebook function FB.api() . I want to wait for the result of this before I continue with some tests, etc. My goal is to create a small helper class to call commonly used functions with this class:

 var fbHelper = { hasPermission: function(permission) { var hasPermission = false; var requestedPermissions = false; var permissions = { }; FB.api('/me/permissions', function(response){ permissions = response; requestedPermissions = true; return response; }); if(permissions){ // make some checking stuff here return hasPermission; } else { console.log('failed to /me/permissions'); return false; } } } 

So, I want to use fbHelper.hasPermission('dummy') . Unfortunately, if(permissions) works until the completion of FB.api() . How can I wait for the rest of my code to complete Api-Call?

+1
source share
3 answers

You cannot write a function that executes an asynchronous request and rely on the possibility of a reliable return of the result. I would restructure your helper method as follows:

 hasPermission: function(permission, callback) { var hasPermission = false; var requestedPermissions = false; var permissions = { }; FB.api('/me/permissions', function(response){ permissions = response; requestedPermissions = true; if (permissions) { callback(permissions); } else { callback(false); } }); } 

Let the calling code provide a callback function that executes when the AJAX call ends.

+1
source

You should move the code to your callback and return from there:

 return FB.api('/me/permissions', function(response){ // this is your callback permissions = response; requestedPermissions = true; if(permissions){ // make some checking stuff here return hasPermission; } else { console.log('failed to /me/permissions'); return false; } }); 
+1
source

If its asynchrony requires a callback, just like you have function(response){} . The fact that javascript is not waiting for the call to complete is the whole purpose of asynchronous calls.

0
source

All Articles