简体   繁体   中英

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.

The javascript SDK doc is here https://developer.yammer.com/docs/js-sdk

What the code currently does is to return an Array of 50 users' profile. 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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM