Is It Conventional to Use Both await and .then() in JavaScript?

asyncecmascriptjavascript

I've written a bit of code that looks like this:

async function fetchData() {
    const json = await fetch(ENDPOINT + key.key).then(data => data.json());
    //Do something with the data
}

It's pretty clear and straight forward what I'm doing here.

I'm just wondering if it's normal to combine both the older Promise style, and the new async/await style like this.

If I wasn't to use .then then I'd be something like this:

async function fetchData() {
    const data = await fetch(ENDPOINT + key.key); 
    const json = await data.json(); 
    //do something with the data
}

Unless I'm missing something here? I guess the question is – is the purpose of async/await to stop using promises completely – or what?

Best Answer

Async await is promises under the hood. So, you can get away with async await most of the time when you have a sequence of dependent async steps to perform.

However, there are times when you want to run a set of operations in series or parallel. There you'll definitely need Promise.all or await in a for loop.

Regarding your code:

  1. You need not await on the return statement of an async function, you can simply return the promise directly.
  2. Keeping a promise in a variable is only needed when you want to do something other than await on it.