Skip to content

Instantly share code, notes, and snippets.

@lantosgyuri
Last active April 22, 2020 07:43
Show Gist options
  • Save lantosgyuri/b0efa24b2632bcec910a7041e926b2e4 to your computer and use it in GitHub Desktop.
Save lantosgyuri/b0efa24b2632bcec910a7041e926b2e4 to your computer and use it in GitHub Desktop.
const array = [
1, 2, 3, 4,
];
const createAsyncfunction = number => new Promise((resolve, reject) => {
const tiemout = Math.floor(Math.random() * Math.floor(10));
if (number === 3) reject('Bad number');
else {
setTimeout(() => {
console.log('number is printed: ', number);
resolve();
}, tiemout * 1000);
}
});
const createFailCatcher = func => async (...items) => {
try {
await func(...items);
} catch (e) {
console.log('error is: ', e);
}
};
// ---------- end of utils
const asyncFucntionWithCatch = createFailCatcher(createAsyncfunction);
const forEach = (func, array) => {
array.forEach(async (item) => {
await func(item);
});
};
const reduce = (func, array) => {
array
.reduce(async (promise, arrayItem) => {
await promise;
return func(arrayItem);
}, Promise.resolve());
};
const promiseAll = async (func, array) => {
await Promise.all(array.map((item) => func(item)));
};
const recursive = (func, array) => {
let iterator = 0;
const reducer = async () => {
if (iterator < array.length) {
await func(array[iterator]);
iterator++;
return reducer();
}
console.log('end');
};
reducer();
};
// console.log(forEach(asyncFucntionWithCatch, array));
// console.log(reduce(asyncFucntionWithCatch, array));
// console.log(promiseAll(asyncFucntionWithCatch, array));
// console.log(recursive(asyncFucntionWithCatch, array));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment