函数执行完毕后继续循环。如何使用jquery延迟

时间:2013-04-29 11:18:47

标签: javascript jquery loops each jquery-deferred

我有以下数据

var data = [{user:"somename"}, {user:"anothername"}];

我有这个功能来处理那个,比如检查用户是否存在

function process(user) {
    $.ajax({
        url: 'http://domain.com/api',
        success: function(result) {
            if(result == 'success')
                anotherFunction();
            else 
                console.log('error');
        }
    })
}

function anotherFunction() {
     $.ajax({

        // do stuffs
     })
}

$。each(data,function(k,v){     处理(v.user); })

$.each将尝试循环process并且anotherFunction尚未完成

问题,在进入另一个索引之前,我该怎样做才能确保所有功能都已完成执行?

我听说我可以使用延迟的jquery。

1 个答案:

答案 0 :(得分:1)

收集您的AJAX函数返回的promise,如有必要,使用.then对结果进行后处理,以便调用anotherFunction() return {em} $.ajax 1}}

function process() {
    return $.ajax(...).then(function(result) {
        if (result === 'success') {
             return anotherFunction();
        } else {
             return null;  // this might need to change...
        }
    });
}

function anotherFunction() {
    return $.ajax(...);
}

var promises = [];
$.each(data, function(k, v) {
    promises.push(process(v.data));
}

然后等待所有承诺得到解决:

$.when.apply($, promises).done(function() {
      // all done here
});

注意:在 general 中,对于AJAX调用来说,为错误生成非2xx返回码是一种很好的做法,而不是“成功”HTTP调用中的错误代码。然后,这允许客户端代码使用正常的AJAX错误处理(即.fail回调),而不是在AJAX成功处理中检查“错误”。

相关问题