Skip to content

Instantly share code, notes, and snippets.

@alexsad
Created June 10, 2024 12:20
Show Gist options
  • Save alexsad/31a8d361031667d06d6b07e7385276dc to your computer and use it in GitHub Desktop.
Save alexsad/31a8d361031667d06d6b07e7385276dc to your computer and use it in GitHub Desktop.
loops with promise
(async () => {
const fakeRefreshComp = (compName: string) => console.log('refresh-comp1:', compName);
const fakeRequest = (durationInSecs: number) => {
return new Promise<number>(success => {
const timeOutId = setTimeout(() => success(timeOutId), durationInSecs * 1000);
})
}
const elementList = [
{
durationRequest: 3,
itemName: 'itemOne',
},
{
durationRequest: .5,
itemName: 'itemTwo',
},
{
durationRequest: 1,
itemName: 'itemThree',
}
];
const example1 = () => {
elementList.forEach(async (item) => {
await fakeRequest(item.durationRequest).then(() => {
console.log('processing... item ', item.itemName);
});
fakeRefreshComp('case 1');
})
}
const example2 = async () => {
for await(let item of elementList){
await fakeRequest(item.durationRequest);
console.log('processing... item ', item.itemName);
}
fakeRefreshComp('case 2');
}
const example3 = async () => {
await Promise.all(elementList.map(async item => {
await fakeRequest(item.durationRequest);
console.log('processing... item ', item.itemName);
}));
fakeRefreshComp('case 3');
}
//wrong real case based
const start = performance.now();
await example1();
const end = performance.now();
console.log(`duration: ${end - start}`);
// with for waiting for each request
const start2 = performance.now();
await example2();
const end2 = performance.now();
console.log(`duration: ${end2 - start2}`);
// with for waiting for each request
const start3 = performance.now();
await example3();
const end3 = performance.now();
console.log(`duration: ${end3 - start3}`);
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment