问题描述
我生病了以下问题:
我使用Facebook的功能查询一些权限的Facebook的API FB.api()
。我想等这个结果之前,我去上进行一些测试,等我的目标是创建一个小的辅助类此类调用常用的功能:
I query the Facebooks API for some permissions by using the facebook function FB.api()
. I want to wait for the result of this before I go on to proceed some tests etc. My aim is to create a small helper class to call often used functions by 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;
}
}
}
所以我想用 fbHelper.hasPermission('假')
。不幸的是,如果(权限)
之前工作FB.Api()
完成。
如何能够做到等待我的code的其余部分,直到API的调用完成??
So i want to use fbHelper.hasPermission('dummy')
. Unfortunately the if(permissions)
is worked before FB.Api()
is completed.How can I achieve to wait for the rest of my code until the Api-Call is completed??
推荐答案
您真的不能编写一个执行一个异步请求的函数,并期望能够可靠地返回结果。我会调整你的helper方法如下:
You can't really write a function that executes an asynchronous request and expect to be able to reliably return 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);
}
});
}
让调用code供应一个回调函数来执行当Ajax调用已完成。
Let calling code supply a callback function to be executed when the AJAX call has completed.
这篇关于等待异步结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!