I have a piece of code:
const finalPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("finalPromise");
}, 1000);
})
const obj = {
nested: {
a: 1,
b: 2
}
}
const p1 = Promise.resolve(3);
const p2 = Promise.reject(22);
const p3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("foo");
}, 3000);
});
new Promise(res => {
for(let i=0; i < 3; i++) {
if(i===0) {
p3.then(r => {
obj.nested.a = 3;
console.log(r)
}).catch(console.log)
}
if(i==1) p2.then(console.log).catch(console.log);;
if(i==2) p1.then(console.log).catch(console.log);
}
res(true); // this won't wait until all promises resolved/rejected
})
.then(() => finalPromise).then(r => console.log(`final ${r}, ${JSON.stringify(obj)}`)) // here we'll get obj with a = 1
.catch(e => console.log(`err ${e}`));
The result of this code run is next:
[LOG]: 3
[LOG]: 22
[LOG]: "final finalPromise, {"nested":{"a":1,"b":2}}"
[LOG]: "foo"
So my question is – can we somehow rewrite the code so we would get to the last then
only after all promises inside the for loop
resolved or rejected(also should be counted as resolved)? I know this can be done with async/await
but it is forbidden for some reason.
I tried to use Promise.all
but couldn’t find the way to count rejected
as resolved
also.