0

我刚刚习惯了$.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.
          })
       }
})

还有一件事,是否可以在循环中使用该函数?例如

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

2 回答 2

0

这里更好地解释了链接承诺:

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");
            }
        });
    });
}
于 2013-05-02T19:17:29.803 回答
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();
}

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

于 2013-05-02T19:04:54.510 回答