jQuery:每个异步后调用函数 [英] JQuery: call function after async each

查看:97
本文介绍了jQuery:每个异步后调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我们有以下代码:

For example we've this code:

$.each([1, 2, 3], function(key, val) {
  gear(val);
});

function gear(params) {
   var values = {1: 'abc', 2: 'cba', 3: 'acb'};
   query(values[params]);
}

function query(settings) {
   $.ajax({
     ...
     settings
     ...
   })
}

我怎样才能等到每次迭代都完成并调用某些东西?

How can i wait until every iteration will completed and call something yet?

推荐答案

您可以使用.reduce()迭代数组,而jQuery ajax承诺对函数调用进行排序:

You can use .reduce() to iterate the array and jQuery ajax promises to sequence the function calls:

[1, 2, 3].reduce(function(p, item) {
    return p.then(function() {
        return gear(item);
    });
}, $.Deferred().resolve()).then(function() {
    // everything done here
});

function gear(params) {
    var values = {1: 'abc', 2: 'cba', 3: 'acb'};
    return query(values[params]);
}

function query(settings) {
   return $.ajax({
     ...
     settings
     ...
   })
}

这将对ajax调用进行排序,以使下一个调用直到上一个调用完成才开始.

This will sequence the ajax calls so the next one doesn't start until the prior one is done.

gear()query()中,您返回$.ajax()已经返回的保证.

In both gear() and query(), you return the promise that $.ajax() already returns.

然后,使用.reduce()遍历累积promise的数组.您传入一个最初解析的Promise,然后数组中的每个项目都会在链的末尾添加.then().

Then, you use .reduce() to iterate the array where you accumulate a promise. You pass in an initially resolved promise and then each item from the array adds a .then() onto the end of the chain.

如果您想同时运行所有Ajax调用,然后在它们全部完成后仅收到通知,则可以执行以下操作:

If you wanted to run all the Ajax calls at the same time and then just get a notification when they are all done, you could do this:

$.when.apply($, [1, 2, 3].map(function(item) {
    return gear(item);
})).then(function(r1, r2, r3) {
    // everything done here
    // results are in arguments[0], arguments[1], ... arguments[n]
});

function gear(params) {
    var values = {1: 'abc', 2: 'cba', 3: 'acb'};
    return query(values[params]);
}

function query(settings) {
   return $.ajax({
     ...
     settings
     ...
   })
}

这篇关于jQuery:每个异步后调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆