Jquery Deferred in each loop with ajax callback

我与影子孤独终老i 提交于 2019-12-01 12:33:25

Your result is as expected.

Your for loop runs synchronously to completion and runs test() twice.

test() then immediately calls test1() so the first thing you see is that test1() gets to run twice. Then, after each test1() completes its promise, it sets the timer for your test() log message. So naturally, the two log messages from test() comes after the two log messages from test1().

Remember that $.when() runs things in parallel so all the promises you pass it are in flight at the same time.

If you want to serialize your calls to test(i) so the next one doesn't happen until after the first one, then you need to do things differently.

Also, you are using an anti-pattern in main() by creating a deferred where you don't need to create one. You can just return $.when.apply(...). You don't need to wrap it in another deferred.


To serialize your calls to test(i) to get the type of output you indicate you wanted, you can do this:

function main() {
    var items = [0, 1];
    return items.reduce(function(p, index) {
        return p.then(function() {
            return test(index);
        });
    }, $.Deferred().resolve());
}

Working demo that generates your desired output: https://jsfiddle.net/jfriend00/hfjvjdcL/

This .reduce() design pattern is frequently used to serially iterate through an array, calling some async operation and waiting for it to complete before calling the next async operation on the next item in the array. It is a natural to use .reduce() because we're carrying one value through to the next iteration (a promise) that we chain the next iteration to. It also returns a promise too so you can know when the whole thing is done.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!