Skip to content

Instantly share code, notes, and snippets.

@yilmazdurmaz
Last active May 31, 2022 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yilmazdurmaz/81cef974ffb5bf5e06585029fb9da405 to your computer and use it in GitHub Desktop.
Save yilmazdurmaz/81cef974ffb5bf5e06585029fb9da405 to your computer and use it in GitHub Desktop.
for of array of promise
let a=[10,20,30,40]
let getit=async(ax,ix,arr)=>{
//console.log(ax,ix,arr)
let time=Math.random()*3000;
let ret=Math.random()>0.3;
console.log(ix,arr[ix],time,ret);
return new Promise((res,rej)=>{
setTimeout(()=>{
if (ret) {
res({msg:"done ",val:arr[ix]});
return
}
else {
rej({msg:"error",val:arr[ix]});
return
}
},time)
})}
// print promises after all settled, and in the order they are in the array
for (let prm of await Promise.allSettled(a.map( (ax,ix,arr)=>getit(ax,ix,arr) )) ){
console.log(prm)
}
// use results after all promises settled, and in the order they are in the array
for (let prm of await Promise.allSettled(a.map( (ax,ix,arr)=>getit(ax,ix,arr) )) ){
switch(prm.status){
case "fulfilled":
console.log(prm.value)
break;
case "rejected":
console.error(prm.reason)
break;
}
}
// prints the promises
// causes "Uncaught (in promise)" error printed
for (let prm of await a.map( (ax,ix,arr)=>getit(ax,ix,arr) ) ){
console.log(prm)
}
// processes the promises, but in the order they resolved/rejected
for (let prm of await a.map( (ax,ix,arr)=>getit(ax,ix,arr) ) ){
prm.then(console.log).catch(console.error)
}
// process promises, but in the order they resolved/rejected
for (let prm of a.map( (ax,ix,arr)=>getit(ax,ix,arr) ) ){
prm.then(console.log).catch(console.error)
}
// for await of, competely different behaviour, halts on first rejection
// uses results, and in the order they are in the array
// causes "Uncaught" in for before halting, and "Uncaught (in promise)" error in promises
for await (let prm of a.map( (ax,ix,arr)=>getit(ax,ix,arr) ) ){
console.log(prm)
}
// exits loop in first rejection, else process results in the order they are in the array
for (let prm of await Promise.all(a.map( (ax,ix,arr)=>getit(ax,ix,arr) ) ) ){
console.log(prm)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment