在 javascript 中进行嵌套承诺调用

Make nested promise call in javascript

本文关键字:嵌套 承诺 调用 javascript      更新时间:2023-09-26

我尝试使用 yammer SDK https://c64.assets-yammer.com/assets/platform_js_sdk.js进行异步调用,如下所示的代码。

javascript SDK 文档在这里https://developer.yammer.com/docs/js-sdk

代码当前的作用是返回一个包含 50 个用户的配置文件的数组。用户总数是不可预测的。

我想要什么:当上一次调用中返回的array.length equal to 50时,即后续页面中可能有更多的用户,使用index++相同的 API URL 进行另一次调用。

重复此操作,直到没有更多要提取的用户。

但是如何制作呢?

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

只需创建一个 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");
        }
    });
})();