Reputation: 1990
I am trying to find the best way to loop through an array, perform an operation on every element of the array and return the result using Q
.
Let's say I have this array:
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);
}
});
Upvotes: 1
Views: 90
Reputation: 5078
If the operation you perform is not asynchronous you can just use regular Array#map and resolve the mapped array:
var operationFunction = function(d) {
return d ? 1 : 0;
};
q(arr.map(operationFunction)).then(function(v) {
v.forEach(function(d) {
console.log(d);
});
});
If your operation is a node.js style asynchronous function you can map the source array to an array of promises, and then wait for them to resolve:
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);
});
});
Or, if the operation function is asynchronous and you can edit it you could use deferred objects:
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);
});
});
Upvotes: 1