Skip to content

Instantly share code, notes, and snippets.

@RobertLucian RobertLucian/test.js
Created Aug 15, 2018

Embed
What would you like to do?
Just an async mapping function in JS
const asyncMap = (array, fn, callback) => {
var output = []; output.length = array.length;
var counter = 0
array.forEach((element, index, array) => {
fn(element, (na, number) => {
output[index] = number
counter++
if (output.length == counter) {
callback(null, output)
}
})
})
}
asyncMap([ 1, 2, 3, 4 ], (number, callback) => {
setTimeout(() => {
if (typeof number !== 'number') {
callback(new Error(`Not a number: ${number}`))
return
}
callback(null, number * number)
}, Math.floor(Math.random() * 100))
}, (error, result) => {
if (error) {
throw error
}
// Should print [ 1, 4, 9, 16 ]
console.log(result)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.