簡體   English   中英

函數完成執行后繼續循環。 如何使用延緩的jQuery

[英]Continue loop after a function has finished executing. How to use jquery deffered

我有以下數據

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){process(v.user);})

$.each甚至會嘗試循環該process ,而anotherFunction尚未完成

問題,我該怎么做才能確保所有功能在移至另一個索引之前都已完成執行?

聽說我可以使用jquery延遲。

收集AJAX函數返回的promise,如有必要.thenanotherFunction()進行后處理,以使其調用anotherFunction() ,后者還必須return $.ajax的結果

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

注意: 一般來說 ,優良作法是AJAX調用生成非2xx錯誤返回碼,而不是“成功” HTTP調用中的錯誤碼。 然后,這允許客戶端代碼使用常規的AJAX錯誤處理(即.fail回調),而不是檢查AJAX成功處理中的“錯誤”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM