Created
October 2, 2019 08:19
-
-
Save noveogroup-amorgunov/86dc9c3667bfafdb5fec126321800453 to your computer and use it in GitHub Desktop.
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
function parallel(arr, callback) { | |
const promises = arr.map(func => { | |
return new Promise((resolve, reject) => { | |
const next = (err, data) => err ? reject(err) : resolve(data); | |
func(next); | |
}); | |
}); | |
Promise | |
.all(promises) | |
.then(result => callback(null, result)) | |
.catch(err => callback(err)); | |
} | |
// Пример использования: | |
function createAsyncFunction(ms) { | |
return function(callback) { | |
setTimeout(() => callback(null, ms), ms); | |
} | |
} | |
function createAsyncThrowErrorFunction() { | |
return function (callback) { | |
callback(new Error('23')); | |
} | |
} | |
parallel( | |
[ | |
createAsyncFunction(5000), | |
createAsyncFunction(3000), | |
createAsyncThrowErrorFunction() | |
], | |
function(err, result) { | |
console.log(err, result); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment