简体   繁体   English

jquery when / then for recursive ajax calls

[英]jquery when / then for recursive ajax calls

function getFriends(url) {
    return FB.api(url, function(response) {
        if (response && !response.error) {
            if (response.paging && response.paging.next) {
                $.each(response.data, function() {
                    friends.push(this);
                });
                return getFriends(response.paging.next);
            } else {
                console.error(friends);
            }
        } else {
            console.error("facebook friends couldn't been retrieved ");
        }
    });
}

$.when(getFriends("/me/friends")).then(
    function() {
        console.log('getFriends finished');
    });

i want to make sure that fb calls finished when the then() block executed but had no chance. 我想确保在执行then()块但没有机会时fb调用完成。 is there a way to implement this ? 有没有办法实现这个?

thanks 谢谢

The Facebook JS SDK does not implement jQuery style promise objects / $.Deferred s but you can easily create an instance on your own like: Facebook JS SDK没有实现jQuery样式的promise对象/ $.Deferred但你可以自己轻松地创建一个实例,如:

function getFriends(url) {
    var dfd = $.Deferred();
    FB.api(url, function(response) {
        if (response && !response.error) {
            if (response.paging && response.paging.next) {
                $.each(response.data, function() {
                    friends.push(this);
                });
                return getFriends(response.paging.next);
            } else {
                console.log(friends);
            }
            dfd.resolve();
        } else {
            console.error("facebook friends couldn't been retrieved ");
            dfd.reject();
        }
    });
    return dfd;
}

getFriends("/me/friends").done(
    function() {
        console.log('getFriends finished');
    }
);

Not really an answer, but a working example that demo's how to go about it: 不是一个真正的答案,而是一个演示如何去做的工作示例:

Demo JSFiddle 演示JSFiddle

function doStuff() {

    var dfd = new jQuery.Deferred();
    alert ("loaded");
    setTimeout(function(){
        dfd.resolve("response - success");
    }, 5000);
    return dfd.promise();

}


$.when(doStuff()).then(function(status) {
    alert(status);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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