如何用Q嵌套序列?

时间:2015-02-10 17:41:26

标签: javascript promise q

我想处理一系列任务,并在完成这些任务的一个块并且每个任务完成后立即获得通知。我期望的输出应该是1,2,3 - 4,5,6 - 7 - 8。根据我目前的实施情况,我得到1,4,7,8 - 2,5 - 3,6

function handleTasks(tasks) {
    var deferred = Q();
    var promises = []

    tasks.forEach(function (task) {
        promises.push(function () {
            return handle(task);
        });
    });

    promises.reduce(Q.when, new Q()).then(function () {
        // Finished inner hunk.
        deferred.resolve();
    });

    return deferred.promise;
}

function handle(t) {
    var deferred = Q.defer();
    document.write("started " + t);

    Q.delay(5000).then(function () {
        document.write("finished " + t);
        deferred.resolve();
    });

    return deferred.promise;
}

var deferred = Q();
var tasks = [[1, 2, 3], [4, 5, 6], [7], [8]];
var promises = []

tasks.forEach(function (task) {
    promises.push(function () {
        return handleTasks(task);
    });
});

promises.reduce(Q.when, new Q()).then(function () {
    // Finished all tasks
    deferred.resolve();
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/q.js/0.9.6/q.js"></script>

1 个答案:

答案 0 :(得分:2)

我真的不确定你的代码是如何产生任何输出的。您尝试使用承诺,就好像它们已被延期一样,并且您正在使用document.write(),我想这会覆盖整个页面。

虽然不一定是个错误,但您使用的是deferred antipattern

所以我不确定你为什么会得到你所做的结果,但这是一种更清洁的方法,可以产生预期的结果:

&#13;
&#13;
function handleTasks(tasks) {
    var promiseFuncs = tasks.map(function (task) {
        return function () {
            return handle(task);
        };
    });

    return promiseFuncs.reduce(Q.when, new Q()).then(function () {
        console.log("finished " + JSON.stringify(tasks));
    });
}

function handle(t) {
   console.log("started " + t);

    return Q.delay(5000).then(function () {
        console.log("finished " + t);
        return t;
    });
}

var tasks = [[1, 2, 3], [4, 5, 6], [7], [8]];
var promiseFuncs = tasks.map(function (task) {
    return function () {
        return handleTasks(task);
    };
});

promiseFuncs.reduce(Q.when, new Q());
&#13;
<script src="http://cdnjs.cloudflare.com/ajax/libs/q.js/0.9.6/q.js"></script>
&#13;
&#13;
&#13;

您还可以使用辅助函数消除一些重复:

&#13;
&#13;
function runSequence(items, action) {
    return items.map(function (item) {
        return function () {
            return action(item);
        };
    }).reduce(Q.when, new Q());
}

function handleTasks(tasks) {
    return runSequence(tasks, handle).then(function () {
        console.log("finished " + JSON.stringify(tasks));
    });
}

function handle(t) {
   console.log("started " + t);

    return Q.delay(5000).then(function () {
        console.log("finished " + t);
        return t;
    });
}

var tasks = [[1, 2, 3], [4, 5, 6], [7], [8]];
runSequence(tasks, handleTasks);
&#13;
<script src="http://cdnjs.cloudflare.com/ajax/libs/q.js/0.9.6/q.js"></script>
&#13;
&#13;
&#13;