[英]Make nested promise call in javascript
I try use yammer SDK https://c64.assets-yammer.com/assets/platform_js_sdk.js
to make async call like the code below. 我尝试使用yammer SDK
https://c64.assets-yammer.com/assets/platform_js_sdk.js
进行异步调用,如下面的代码。
The javascript SDK doc is here https://developer.yammer.com/docs/js-sdk
javascript SDK文档在这里
https://developer.yammer.com/docs/js-sdk
What the code currently does is to return an Array of 50 users' profile. 该代码当前执行的操作是返回一个由50个用户的个人资料组成的数组。 The total number of users is unpredictable.
用户总数不可预测。
What I want: When the returned array.length
in previous call is equal to 50
, ie there could be more users in following page, make another call with index++
to the same API URL. 我想要的是:当先前调用中返回的
array.length
equal to 50
,即在下一页中可能会有更多用户,请使用index++
再次调用相同的API URL。
This is repeated until there is no more users to be fetched. 重复此操作,直到没有更多用户要获取为止。
But how to make it? 但是如何做到呢?
yam.connect.loginButton('#yammer-login', function (resp) { console.log(resp.authResponse); var index = 1; if (resp.authResponse) { //trigger data process yam.platform.request({ url: "users.json",
method: "GET", data: {
"page": index }, success: function (user) { console.log("The request was successful."); console.log(user.length); }, error: function (user) { console.log("There was an error with the request."); } }); }else{ console.log("error to get access_token"); } });
Simply by creating a getUsers
function and a global variable (in this case I've scoped it all through an immediately-invoked function ) to control index you can just check if users length is 50, and if so - run the function again: 简单地通过创建一个
getUsers
函数和一个全局变量(在本例中,我通过一个立即调用的函数将其范围限定在内)来控制索引,您可以仅检查用户长度是否为50,如果是,请再次运行该函数:
(function() {
var index = 1;
var getUsers = function() {
yam.platform.request({
url: "users.json",
method: "GET",
data: {
"page": index
},
success: function (user) {
console.log("The request was successful.");
console.log(user.length);
if (user.length === 50) {
// There are additonal users - increment index and run the function again
index++;
getUsers();
}
},
error: function (user) {
console.log("There was an error with the request.");
}
});
};
yam.connect.loginButton('#yammer-login', function (resp) {
console.log(resp.authResponse);
if (resp.authResponse) {
//trigger data process
getUsers();
} else {
console.log("error to get access_token");
}
});
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.