Skip to content

JavaScript then vs await

  • by

JavaScript then and await are two approaches for handling asynchronous operations. then is used with promises to handle resolved values or errors in a chained manner. On the other hand, await is used within async functions to pause execution until a promise is resolved, resulting in more synchronous-like code.

Comparing the two, await offers a cleaner and more readable syntax, making it the preferred choice for handling asynchronous operations in modern JavaScript development.

Here’s a comparison of the syntax for using then and await in JavaScript:

then:

asyncFunction()
  .then(function(result) {
    // Handle resolved value
  })
  .catch(function(error) {
    // Handle error
  });

await:

async function myFunction() {
  try {
    const result = await asyncFunction();
    // Handle resolved value
  } catch (error) {
    // Handle error
  }
}

Here’s a tabular format comparing the different approaches in JavaScript for handling asynchronous operations: callbacks, promises with then, and async/await.

ApproachDescriptionExample
CallbacksUsing callback functions as arguments to handle asynchronous operations.function fetchData(callback) {
setTimeout(function() {
callback('Data fetched');
}, 2000);
}
fetchData(function(result) {
console.log(result);
});
Promises with thenUsing promises to represent asynchronous operations and chaining then methods to handle resolved values or errors.function fetchData() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('Data fetched');
}, 2000);
});
}
fetchData()
.then(function(result) {
console.log(result);
})
.catch(function(error) {
console.error(error);
});
async/awaitUsing async functions and await keyword to write asynchronous code in a more synchronous-like manner.function fetchData() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('Data fetched');
}, 2000);
});
}
async function doWork() {
try {
const result = await fetchData();
console.log(result);
} catch (error) {
console.error(error);
}
}
doWork();

JavaScript then vs await examples

simple example code comparing the usage of then and await in JavaScript:

Example using then:

function fetchData() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve('Data fetched');
    }, 2000);
  });
}

fetchData()
  .then(function(result) {
    console.log(result); // Handle resolved value
  })
  .catch(function(error) {
    console.error(error); // Handle error
  });

Example using await:

function fetchData() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve('Data fetched');
    }, 2000);
  });
}

async function doWork() {
  try {
    const result = await fetchData();
    console.log(result); // Handle resolved value
  } catch (error) {
    console.error(error); // Handle error
  }
}

doWork();

Complete code

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Async Examples</title>
</head>
<body>
  <h1>JavaScript Async Examples</h1>

  <h2>Using "then" with Promises</h2>
  <div id="thenExample"></div>

  <h2>Using "await" with async/await</h2>
  <div id="awaitExample"></div>

  <script>
    function fetchData() {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          resolve('Data fetched');
        }, 2000);
      });
    }

    // Example using "then" with Promises
    fetchData()
      .then(function(result) {
        document.getElementById('thenExample').textContent = result;
      })
      .catch(function(error) {
        document.getElementById('thenExample').textContent = 'Error: ' + error;
      });

    // Example using "await" with async/await
    async function doWork() {
      try {
        const result = await fetchData();
        document.getElementById('awaitExample').textContent = result;
      } catch (error) {
        document.getElementById('awaitExample').textContent = 'Error: ' + error;
      }
    }

    doWork();
  </script>
</body>
</html>

Output:

JavaScript then vs await

Comment if you have any doubts or suggestions on this Js difference topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *