Created
August 15, 2018 19:40
-
-
Save RobertLucian/8cec33c5044971ecece73f7cfc6de3d5 to your computer and use it in GitHub Desktop.
Just an async mapping function in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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