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() {
  let example = await fetch('');
  console.log('I will print second');

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() {
  let example = fetch('').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');


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 (1)

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.

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post