等待异步结果

我厌倦了以下问题:

我使用facebook函数FB.api()在Facebooks API中查询某些权限。 我想在继续进行一些测试之前等待结果。我的目标是创建一个小助手类来调用这个类经常使用的函数:

 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; } } } 

所以我想使用fbHelper.hasPermission('dummy') 。 不幸的是,在FB.Api()完成之前, if(permissions)工作。 如何在Api-Call完成之前等待其余的代码?

您无法真正编写执行异步请求的函数,并期望能够可靠地返回结果。 我会重构您的帮助方法,如下所示:

 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); } }); } 

让调用代码提供一个在AJAX调用完成时执行的回调函数。

您应该将代码移动到回调中并从那里返回:

 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; } }); 

如果它是异步的,你需要有一个回调,就像你有function(response){} 。 javascript不等待调用结束的事实是异步调用的全部目的。