'how to resolve array promise and then call the other method
function resolveThisFirst() {
let newArr = [];
for (let i = 0; i < 5; i++) {
setTimeout(() => {
newArr.push(i);
}, 2000);
}
return Promise.all(newArr);
}
function afterThis() {
console.log("Call this first after array resolve value");
}
resolveThisFirst()
.then(afterThis)
.catch((err) => console.log(err));
I am trying to resolve the array value first then call afterThis function. how can we get this function work.
Thank You
Solution 1:[1]
You need to push promises to array, here you were just adding numbers.
function getPromise(time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`I have resolved in ${time} ms`);
}, time);
});
}
function resolveThisFirst() {
let newArr = [];
for (let i = 0; i < 5; i++) {
newArr.push(getPromise(i * 1000));
}
console.log(
`Promises are ready at ${new Date()} but they will take some time to resolve`
);
return Promise.all(newArr);
}
function afterThis() {
console.log('Call this first after array resolve value');
}
resolveThisFirst()
.then((data) => {
console.log(`Promises resolved at ${new Date()}`);
afterThis();
})
.catch((err) => console.log(err));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Devesh |
