简体   繁体   中英

Javascript SDK: can i have another FB.api() calls inside FB.api()

// count total no. of groups created by me
function totalGroups(response) {
    FB.api('/me/groups', {fields:'owner'}, function(g_response) {
        for (i in g_response.data) {
            FB.api('/me', function(m_response) {
                var c = 0;
                if (g_response.data[i].owner.name == m_response.name) {
                    c++;
                }
            });
        }
        console.log('Total:' +c);
  });
}

hi, can i have another FB.api() calls inside FB.api() like i do on the above code because i can't get the value for if (g_response.data[i].owner.name == m_response.name)

Yes, you can embed a FB.api() call inside another Fb.api() call but the flow is guaranteed as the FB.api() calls are asynchronous. One issue I found with your code is related to the var c . First of all it's out of scope for console.log('Total:' +c) method and moreover you have declared it inside the loop which means it's value will be reset after each loop execution.

Try this:

// count total no. of groups created by me
function totalGroups(response) {
    var c = 0;
    FB.api('/me/groups', {fields:'owner'}, function(g_response) {
        for (i in g_response.data) {
            FB.api('/me', function(m_response) {               
                if (i.owner.name == m_response.name) {
                    c++;
                }
            });
        }
        console.log('Total:' +c);
});
}

this is how i fix the problem, i know its ugly but it's the best i can do at the moment.

function totalGroups(response) {
    var c = 0;
    FB.api('/me', function(m_response) {
        FB.api('/me/groups', {fields:'owner'}, function(g_response) {
            for (i in g_response.data) {            
                if (g_response.data[i].owner) {
                    if (g_response.data[i].owner.name == m_response.name) {     
                        c++;
                    }
                }
            }
            console.log('Total: ' + c);
        });
    });
}

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