Skip to content

Instantly share code, notes, and snippets.

@RobertLucian
Created August 15, 2018 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobertLucian/8cec33c5044971ecece73f7cfc6de3d5 to your computer and use it in GitHub Desktop.
Save RobertLucian/8cec33c5044971ecece73f7cfc6de3d5 to your computer and use it in GitHub Desktop.
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