- Source:
Examples
// array
var order = [];
var collection = [1, 3, 2, 4];
var iterator = function(result, num, done) {
setTimeout(function() {
order.push(num);
result.push(num)
done();
}, num * 10);
};
async.transform(collection, iterator, function(err, res) {
console.log(res); // [1, 2, 3, 4]
console.log(order); // [1, 2, 3, 4]
});
// array with index and accumulator
var order = [];
var collection = [1, 3, 2, 4];
var iterator = function(result, num, index, done) {
setTimeout(function() {
order.push([num, index]);
result[index] = num;
done();
}, num * 10);
};
async.transform(collection, {}, iterator, function(err, res) {
console.log(res); // { '0': 1, '1': 3, '2': 2, '3': 4 }
console.log(order); // [[1, 0], [2, 2], [3, 1], [4, 3]]
});
// object with accumulator
var order = [];
var object = { a: 1, b: 3, c: 2, d: 4 };
var iterator = function(result, num, done) {
setTimeout(function() {
order.push(num);
result.push(num);
done();
}, num * 10);
};
async.transform(collection, [], iterator, function(err, res) {
console.log(res); // [1, 2, 3, 4]
console.log(order); // [1, 2, 3, 4]
});
// object with key
var order = [];
var object = { a: 1, b: 3, c: 2, d: 4 };
var iterator = function(result, num, key, done) {
setTimeout(function() {
order.push([num, key]);
result[key] = num;
done();
}, num * 10);
};
async.transform(collection, iterator, function(err, res) {
console.log(res); // { a: 1, b: 3, c: 2, d: 4 }
console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b'], [4, 'd']]
});