async-array-methods
Async methods to manipulate arrays.
Usage
var methods = require('async-array-methods')
var AsyncArray = methods.Array
var filter = methods.filter
var map = methods.map
var forEach = methods.forEach
var reduce = methods.reduce
All methods return a promise.
Methods
Callbacks can be made asynchronous
by returning a promise, or
accepting a function argument,
which will be called when the callback finishes.
Otherwise, the callback is treated as synchronous.
filter
Signature: filter(arr, fn, context)
filter(
[1, 2, 3, 4],
function (v, i, a, next) {
process.nextTick(function () {
next(null, v % 2)
})
}
)
.then(function (res) {
console.log(res)
})
map
Signature: map(arr, fn, context)
fn
is called with each element in parallel.
map(
[1, 2, 3, 4],
function (v) {
return new Promise(function (rs) {
process.nextTick(function () {
rs(v << 2)
})
})
},
{ num: 2 }
)
.then(console.log.bind(console))
series
This method works like map
,
except that fn
is called with each element in sequence rather than in parallel.
Signature: map(arr, fn, context)
var n = 1
series(
[1, 2, 3, 4],
function (v, i, arr, next) {
var delay = rand()
console.log('i:', i, 'delay:', delay)
setTimeout(function() {
next(null, v << n++)
}, delay)
}
)
.then(log)
function rand() {
return Math.floor(Math.random() * 10) * 10
}
forEach
fn
is called with elements in sequence.
Signature: forEach(arr, fn, context)
var count = 0
forEach(
[1, 2, 3, 4],
function (v, i, _, next) {
process.nextTick(function () {
console.log(count++, i)
next(null, v << 2)
})
}
)
.then(function (arr) {
console.log(arr)
})
reduce
Signature: reduce(arr, fn, initial)
reduce(
[1, 2, 3, 4],
function (a, b, i, arr, next) {
process.nextTick(function () {
next(null, a + b)
})
}
)
.then(console.log.bind(console))
AsyncArray
Signature: AsyncArray(arr)
Methods:
map
series
filter
forEach
reduce
var origin = AsyncArray([1, 2, 3, 4, 5, 6])
var odd = origin.filter(isOdd)
var even = origin.filter(isEven)
return odd.then(function (res) {
console.log(res)
return even
})
.then(function (res) {
console.log(res)
})
.then(function () {
return even.reduce(flagMap, {})
})
.then(function (res) {
console.log(res)
})
.then(function () {
return origin.filter(isOdd).reduce(flagMap, {})
})
.then(function (res) {
console.log(res)
})
function isOdd(n, i, arr, next) {
process.nextTick(function () {
next(null, n % 2)
})
}
function isEven(n, i, arr, next) {
return new Promise(function (resolve) {
process.nextTick(function () {
resolve((n + 1) % 2)
})
})
}
function flagMap(o, v) {
o[v] = true
return o
}