循环中的异步承诺

时间:2014-10-23 16:46:25

标签: jquery sharepoint for-loop promise

var deferred = $.Deferred();

function doSomething() {
    for (i = 1; i < 10; i++) {
        context.executeQueryAsync(function () //success function
        {
            if (check_i_val(i)) {
                context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
            }
        },

        function (sender, args) //failure function
        {
            console.log(args.get_message());
        });
    }
}

function success() {
    console.log(i);
}

function failed() {
    //display error
}

function check_i_val(val) {
    if (val = 1 || val = 3 || val = 5 || val = 7) {
        return true;
    }
}

我希望这个按顺序生成1,3,5,7 - 我使用的实际功能比这更复杂并且有加载时间因此结果是意外的。我如何使用deferred(作为jquery promise)以便我的代码按顺序运行?

1 个答案:

答案 0 :(得分:1)

function mockExecuteQueryAsync(inValue) {
    var outValue = $.Deferred();

    window.setTimeout(function() {
        window.console.debug(Date.now(), 'Resolving ', inValue);
        // Let's just return the value we got as input
        outValue.resolve(inValue);
    }, Math.random() * 10000); // Random interval...

    return outValue.promise();
}

var arrayOfPromises = [];
var arrayOfValues = [1, 3, 5, 7];
for (var i in arrayOfValues) {
    arrayOfPromises.push(mockExecuteQueryAsync(arrayOfValues[i]));
}
$.when.apply($, arrayOfPromises).done(function() {
    window.console.debug(Date.now(), 'And now we have all the results...');
    for (var i in arguments) {
        window.console.log(arguments[i]);
    }
});