Member-only story

‘For/Await/Of’ Loops: A Beautiful ES9+ feature

Dr. Ashish Bamania
2 min readMay 30, 2022

Callbacks in JS were made simpler by elegantly defined Promises and later by using the Async/Await syntax.

ES9+ JS introduces another feature to make our lives easier.

Let’s talk about this using the Star Wars API.

Star Wars API Preview

Old Way

To fetch the details of many people from this API, we will define an array of people below.

const urls = [
"https://swapi.dev/api/people/1",
"https://swapi.dev/api/people/2",
"https://swapi.dev/api/people/3"
];

Let’s fetch them using Promises.

Promise.all(urls.map(url => {
return fetch(url).then(result => result.json())
})).then(
array => {
console.log(array[0]);
console.log(array[1]);
console.log(array[2]);
}
).catch(error => console.log("error", error));

This will return the details of people.

Data received using the old syntax

New Way

With the new ES9+ features, we can use the for/await /of syntax with the async keyword.

const urls = [
"https://swapi.dev/api/people/1",
"https://swapi.dev/api/people/2"…

--

--

Dr. Ashish Bamania
Dr. Ashish Bamania

Written by Dr. Ashish Bamania

🍰 I simplify the latest advances in AI, Quantum Computing & Software Engineering for you | 📰 Subscribe to my newsletter here: https://intoai.pub

No responses yet