`I’ve made calls to six built-in APIs within a for loop, where each API call depends on the result of the previous one. I’ve attempted to execute these API calls synchronously; however, due to varying response times, achieving true synchronicity has proven challenging.
for (let i = 0; i < 2; i++) {
let promise1 = new Promise((resolve, reject) => {
resolve("Promise 1 ");
});
let promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise 2");
}, 1000);
});
let promise3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise 3");
}, 2000);
});
let promiseExecution = async () => {
for (let promise of [promise2, promise3, promise1]) {
// console.log('promise',promise)
try {
const message = promise;
console.log(message);
} catch (error) {
console.log(error.message);
}
}
};
promiseExecution();
}
Expected:
promise 2
promise 3
promise 1
promise 2
promise 3
promise 1
2
Answers
If your wanting to wait for an array of promises, you can use
Promise.all()
Below is an example, I’ve also used another function
run
, to also make your loop async, as you also want toawait promiseExecution();
You’re just missing two
await
operators. You need one to get themessage
, and one to awaitpromiseExecution()
. For the latter you need to wrap the whole script in an async function.However, you create the three promise objects at the same time, so that does not really reflect your actual case where "each API call depends on the result of the previous one". If they are dependent, then you would only create the second promise after the first one resolves, …etc.
So I would turn these into three functions that when called, create their respective promise:
Note that I moved the error handling to the outermost layer, as it is not helpful to catch an error in a middle layer, which then rejects the promise returned by the
async
function, only to leave that rejection unhandled.