DEV Community

Discussion on: Using Async/Await: The right way

Collapse
 
simonlegg profile image
Simon • Edited

This is a great write up of a common problem, I would even go one step further and suggest that for your second example could be improved even more

async function withAwaitAsyncData() {
    const responsePokemon = await axios('https://pokeapi.co/api/v2');
    const responseDigimon = axios('https://digimon-api.herokuapp.com/api/digimon');

    // do pokemon stuff

    // do digimon stuff
}
async function withAwaitAsyncData() {
    const responsePokemon = axios('https://pokeapi.co/api/v2');
    const responseDigimon = axios('https://digimon-api.herokuapp.com/api/digimon');

    await responsePokemon;
    // do pokemon stuff

    await responseDigimon
    // do digimon stuff
}

Since the request to the digimon API doesn’t rely on the pokemon API response, you could trigger them separately and only await on the Promise once you need it.

Collapse
 
jamesthomson profile image
James Thomson

Perhaps I'm misunderstanding your suggestion, but you either need to assign the result to a variable or use the Promises' chain.

e.g.

const responsePokemon = axios('https://pokeapi.co/api/v2');

await responsePokemon;

Object.keys(responsePokemon.data).forEach(el => console.log(el))

will result in a TypeError.

So you need to write it as

const responsePokemon = axios('https://pokeapi.co/api/v2');
const res = await responsePokemon;
Object.keys(res.data).forEach(el => console.log(el))

which defeats the purpose (depending on the use case, the Promise may be intended to be used later)

or

const responsePokemon = axios('https://pokeapi.co/api/v2');
await responsePokemon.then(({data}) => Object.keys(data).forEach(el => console.log(el)));
Collapse
 
ogzhanolguncu profile image
Oğuzhan Olguncu • Edited

Thanks for clarifying it. That was exactly what I was trying to say, If you don't need it that exact moment you do not have to await it. This is one of pitfalls of async/await.