<tutorialjinni.com/>

.then() and .await() JavaScript With Examples

Posted Under: JavaScript, Programming, Tutorials on Mar 21, 2023
.then() and .await() JavaScript With Examples
The .then() and .await() functions are two of the most commonly used asynchronous functions in JavaScript. While they both have the same purpose of allowing code to run asynchronously, the way they are used and the way they work are very different.

The .then() function is used to register a callback function that will be executed once a promise is resolved. It takes two parameters: the first one is a success callback and the second one is a failure callback. The success callback will be executed when the promise is fulfilled and the failure callback will be executed when the promise is rejected. The following example shows how to use the .then() function:
let promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Success!');
  }, 1000);
});

promise.then((result) => {
  console.log(result);
}, (error) => {
  console.log(error);
});
The .await() function is used to pause the execution of the current function until the promise is resolved. It takes one parameter, which is the promise that needs to be resolved. The await keyword will pause the execution of the current function until the promise is either resolved or rejected. The following example shows how to use the .await() function:
async function doSomething() {
  let promise = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Success!');
    }, 1000);
  });
  let result = await promise;
  console.log(result);
}

doSomething();
In nutshell, the .then() and .await() functions are two of the most commonly used asynchronous functions in JavaScript. While they both have the same purpose of allowing code to run asynchronously, the way they are used and the way they work are very different. The .then() function is used to register a callback function that will be executed once a promise is resolved, while the .await() function is used to pause the execution of the current function until the promise is resolved.


imgae