2016-10-28 29 views
0

我有一个元素数组var arr = [1, 2, 3, 4, 5, 6, 7, 8]。我想要的是采取每一个元素,做一些事情,并采取其他。我不希望这些东西并行。节点Q - 使用Q的手柄阵列

例如:

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

我怎样才能做到这一点与Q

回答

1

要将项目数组转换为按顺序处理的承诺数组,可以使用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