DEV Community

Mastering JS
Mastering JS

Posted on

Using `then()` vs Async/Await in JavaScript

When making async requests, you can either use then() or async/await. Async/await and then() are very similar.
The difference is that in an async function, JavaScript will pause the function execution until the promise settles. With then(), the rest of the function will continue to execute but JavaScript won't execute the .then() callback until the promise settles.

async function test() {
  console.log('Ready');
  let example = await fetch('http://httpbin.org/get');
  console.log('I will print second');
}

test();
console.log('I will print first');

Enter fullscreen mode Exit fullscreen mode

If you use promise chaining with then(), you need to put any logic you want to execute after the request in the promise chain. Any code that you put after fetch() will execute immediately, before the fetch() is done.

function test() {
  console.log('Ready');
  let example = fetch('http://httpbin.org/get').then((res) => {
    console.log('This is inside the then() block');
  });
  console.log('This is after the fetch statement where we are now executing other code that is not async');

}

test();
console.log('this is after the entire function');
Enter fullscreen mode Exit fullscreen mode

We recommend using async/await where possible, and minimize promise chaining. Async/await makes JavaScript code more accessible to developers that aren't as familiar with JavaScript, and much easier to read.

Top comments (2)

Collapse
 
lexiebkm profile image
Alexander B.K.

In my 1st experience, with minimal knowledge and skill (lack of the knowledge of async-await), I relied upon fetch API to do request to server. I tried to work around the problem I encountered with my own solution, although I thought it was not the right one. I wished I knew async-await then : I could have had better solution instead of using merely promises chaining.
That being said, I think both approaches have their own best fit depending on the situation.

Collapse
 
katyi profile image
Alexandra Egorova • Edited

This is the best explanation! I read 10 articles before but only your explanation is more clear, thanks a lot!!!