How to use.then( ) Method in Javascript

  • In this code example, we have created a variable createPromise which is a promise having two callbacks provided by javascript.
  • resolve: when the promise resolves successfully.
  • reject: when the promise is rejected for any reason.
  • Then creating setTimeout has a callback function that will run after two seconds.
  • By using the .then( ) method access the value of the Promise.

Example: The code example shows how to access the value of a Promise in JavaScript using the .then method.

Javascript




console.log("wait for 2 seconds to get promise resolved")
const createPromise = new Promise(
    (resolve, reject) => {
        setTimeout(function () {
            resolve(
                "the promise is resolved after 2 seconds");
        }, 2000)
    });
 
createPromise.then((promisedata) => {
    console.log("Promise is resolved successfully", promisedata)
})


Output:

access the Value of a Promise in JavaScript Using .then Method

How to access the Value of a Promise in JavaScript

In this article, we will see how to access the value of Promise in JavaScript. The Promise is a feature of ES6 introduced in 2015. The concept of Promises is generally used when we want to work asynchronously.

The value of a Promise can be accessed in JavaScript using the following methods.

Table of Content

  • Using .then( ) Method
  • Using the Async/Await Method

Syntax:

let promise = new Promise((resolve, reject)=>{//enter the code})

Similar Reads

Approach: Using .then( ) Method

In this code example, we have created a variable createPromise which is a promise having two callbacks provided by javascript. resolve: when the promise resolves successfully. reject: when the promise is rejected for any reason. Then creating setTimeout has a callback function that will run after two seconds. By using the .then( ) method access the value of the Promise....

Approach 2: Using the Async/Await Method

...

Contact Us