Member-only story
‘For/Await/Of’ Loops: A Beautiful ES9+ feature
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.
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.
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"…