我试图找到循环数组的最佳方法,对数组的每个元素执行操作并使用Q
返回结果。
假设我有这个数组:
var q = require('q');
var arr = [1, '2', "3", "undefined", undefined];
var values = [];
q.fcall(
function(){
arr.forEach(d){
if (d){
values.push(1);
}
else{
values.push(0);
}
}
return values;
}
).then(
function(v){
v.forEach(d){
console.log(d);
}
});
答案 0 :(得分:1)
如果您执行的操作不是异步的,您可以使用常规Array#map并解析映射的数组:
var operationFunction = function(d) {
return d ? 1 : 0;
};
q(arr.map(operationFunction)).then(function(v) {
v.forEach(function(d) {
console.log(d);
});
});
如果您的操作是node.js样式异步函数,您可以将源数组映射到promises数组,然后等待它们解析:
var operationFunction = function(d, done) {
process.nextTick(function() {
done(null, d ? 1 : 0);
});
};
var wrapperFunction = function(d) {
return q.nfcall(operationFunction, d);
};
q.all(arr.map(wrapperFunction)).then(function(v) {
v.forEach(function(d) {
console.log(d);
});
});
或者,如果操作函数是异步的并且您可以编辑它,则可以使用延迟对象:
var operationFunction = function(d) {
var deferred = q.defer();
process.nextTick(function() {
deferred.resolve(d ? 1 : 0);
});
return deferred.promise;
};
q.all(arr.map(operationFunction)).then(function(v) {
v.forEach(function(d) {
console.log(d);
});
});