Let’s say you have an array, and you need to run a promise on each of its element synchronously, like this
When you run that script, you get this output
_11Get pokemon from https://pokeapi.co/api/v2/pokemon/1/_11Get pokemon from https://pokeapi.co/api/v2/pokemon/2/_11Get pokemon from https://pokeapi.co/api/v2/pokemon/3/_11Get pokemon from https://pokeapi.co/api/v2/pokemon/4/_11Get pokemon from https://pokeapi.co/api/v2/pokemon/5/_11Script finished..._11Pokemon: ivysaur with id: 2_11Pokemon: bulbasaur with id: 1_11Pokemon: charmeleon with id: 5_11Pokemon: venusaur with id: 3_11Pokemon: charmander with id: 4
Notice that, we run the promise, in this case fetch asynchronously. even though we modify the script to use async await like code below, it doesn’t matter it will give the same result
Still get the same output right??, now how to run it synchronously??.
Instead using Array.forEach
we can use for
loop like this
this code is the trick to run async await in top level javascript file.
_10(async () => {_10 // your async await code_10})();
you get output like this, which means it run synchronously or sequential one by one.
_11Get pokemon from https://pokeapi.co/api/v2/pokemon/1/..._11Pokemon sync: bulbasaur with id: 1_11Get pokemon from https://pokeapi.co/api/v2/pokemon/2/..._11Pokemon sync: ivysaur with id: 2_11Get pokemon from https://pokeapi.co/api/v2/pokemon/3/..._11Pokemon sync: venusaur with id: 3_11Get pokemon from https://pokeapi.co/api/v2/pokemon/4/..._11Pokemon sync: charmander with id: 4_11Get pokemon from https://pokeapi.co/api/v2/pokemon/5/..._11Pokemon sync: charmeleon with id: 5_11Finished
But that is not at all pretty☺
Okay, let’s make it better by creating a function and callback like this
_10const asyncForEach = async (array, callback) => {_10 for (let index = 0; index < array.length; index++) {_10 await callback(array[index], index, array);_10 }_10};
Now your script gonna look like this
Much better, and it’s work
_11Get pokemon from https://pokeapi.co/api/v2/pokemon/1/..._11Pokemon: bulbasaur with id: 1_11Get pokemon from https://pokeapi.co/api/v2/pokemon/2/..._11Pokemon: ivysaur with id: 2_11Get pokemon from https://pokeapi.co/api/v2/pokemon/3/..._11Pokemon: venusaur with id: 3_11Get pokemon from https://pokeapi.co/api/v2/pokemon/4/..._11Pokemon: charmander with id: 4_11Get pokemon from https://pokeapi.co/api/v2/pokemon/5/..._11Pokemon: charmeleon with id: 5_11Finished
Oh you need the typescript version??, here we go