使用延迟链接两个以上的任务,这可以用于循环吗?

时间:2013-05-02 18:43:04

标签: javascript jquery loops deferred

我刚刚习惯$.Deferred,而且我需要使用$.Deferred - then链接三个任务。 我创建了一个函数:

function processA(param1, param2) {
    log = $.post('http://domain.com/process',
                {
                   id: param1,
                   another: param2
                }
           ),
           set = log.then(function(html){
                if (someCondition) {
                    console.log('Successful');
                    // i want to do another ajax call here
                    // and chain another, that does an ajax again
                }
           })
}

我如何做到这一点,如我的代码的评论中所述。 这样对吗?没有经过测试,只是在输入时想到了。

set = log.then(function(html){
      if (someCondition) {
          console.log('Successful');
          $.post(....),
          def = set.then(function(data){
             // i want to do another thing here.
          })
       }
})

另外,是否可以在循环中使用该函数? e.g。

data = [{param1:"...", param2:"..."}, {..., ...}]
$.each(data, function(k,v){
    processA(v.param1, v.param2);
})

2 个答案:

答案 0 :(得分:0)

这是我为骰子游戏写的东西。滚动骰子,每个dice.roll()都存储在$.Deferred对象中。当所有骰子都运行动画时,您可以执行回调或其他任何操作。

var promises = [];

// collect promises
_.each(fDice, function (die) {
    promises.push(function () {
        return $.Deferred(function (dfd) {
            $(die).roll(options, function (data) {
                dfd.resolve(data); // resolve the state
            });
        }).promise(); // send it back
    });
});

// roll selected dice
dfrAll(promises).done(function () {
    // do something here
});

dfrAll: function (array) {
    /// <summary>Resolves n $.Deferred functions from an Array</summary>
    /// <param name="Array" type="Array">An Array of $.Deferred functions</param>
    /// <returns type="Deferred" />
    var dfd = $.Deferred(),
        len = array.length,
        results = [];

    if (len === 0) {
        dfd.resolve(results);
    } else {
        for (var i = 0; i < len; i++) {
            var promise = array[i];
            $.when(promise()).then(function (value) {
                results.push(value);
                if (results.length === len) {
                    dfd.resolve(results);
                }
            });
        }
    }

    return dfd.promise();
}

对我来说,将延迟函数存储到数组中是解决我的动画的关键。希望它有所帮助。

答案 1 :(得分:0)

Here更好地解释了链接承诺:

function authenticate() {
    return getUsername()
    .then(function (username) {
        return getUser(username);
    })
    // chained because we will not need the user name in the next event
    .then(function (user) {
        return getPassword()
        // nested because we need both user and password next
        .then(function (password) {
            if (user.passwordHash !== hash(password)) {
                throw new Error("Can't authenticate");
            }
        });
    });
}