Skip to content

Instantly share code, notes, and snippets.

@robertoandres24
Forked from anvk/promises_reduce.js
Last active October 17, 2021 21:34
Show Gist options
  • Save robertoandres24/0e6fbbfca1c3b935669dcb0fb5da52f6 to your computer and use it in GitHub Desktop.
Save robertoandres24/0e6fbbfca1c3b935669dcb0fb5da52f6 to your computer and use it in GitHub Desktop.
Sequential execution of Promises using reduce()
//recibe un array y una callback asyncrona
// y cada promesa se va ejecutando secuencialmente
// seria lo contrario a un Promise.all()
// me fue util para manejar los insert en la bd con typeorm y evitar conflictos de ids, duplicacion y fallos en las queries
export const runPromisesSequentally = async (
arr: any,
asyncFn: (item: any) => Promise<any>
): Promise<any[]> => {
const allContents = [];
for (const x of arr) {
allContents.push(await asyncFn(x));
}
return allContents;
};
function asyncFunc(e) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(e), e * 1000);
});
}
const arr = [1, 2, 3];
let final = [];
function workMyCollection(arr) {
return arr.reduce((promise, item) => {
return promise
.then((result) => {
console.log(`item ${item}`);
return asyncFunc(item).then(result => final.push(result));
})
.catch(console.error);
}, Promise.resolve());
}
workMyCollection(arr)
.then(() => console.log(`FINAL RESULT is ${final}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment