节点Q - 用Q处理数组

时间:2016-10-28 09:29:31

标签: arrays node.js q

我有一系列元素var arr = [1, 2, 3, 4, 5, 6, 7, 8]。我想要的是采取每一个元素,做一些事情,并采取另一个。我不希望这些东西并行完成。

例如:

arr.forEach(function(d){
   //send 'd' through HTTP
   //if send is success wait 1000 resend the same.      
});

如何使用Q

执行此操作

1 个答案:

答案 0 :(得分:1)

要将项目数组转换为顺序处理的promises数组,可以使用reduce

var Q = require('q'); 

var arr = [1, 2, 3, 4, 5, 6, 7, 8];

var lastPromise = arr.reduce(function(promise, item) {
    return promise.then(function() {
        return someFunc(item);
    });
}, Q.resolve())


lastPromise.then(function() {
    console.log('some message');
})
.catch(function(error) {
    console.log('some error');
});

此处someFunc正在处理您的项目,如此

var item = 'item1';

someFunc(item).then(function(result) {
       console.log("The task finished.");
})
.catch(function(error) {
       console.log(error);
});

arr.reduce()接受两个参数,一个回调和一个初始值。如果你注意到它们传递给reduce()的第二个参数,它现在将为数组中的每个元素调用给定的回调。回调有两个参数。第一次,第一个参数是初始值,第二个参数是数组的第一个元素。下一次,第一个参数是前一次调用回调的返回值,第二个参数是数组的下一个元素。

有关详细信息,请查看 https://joost.vunderink.net/blog/2014/12/15/processing-an-array-of-promises-sequentially-in-node-js