Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptHow to access object properties from result returned by async() function in...

How to access object properties from result returned by async() function in JavaScript ?

In this article, we will see how to access the properties of a javascript object result returned by the async() function in Javascript.

A javascript object property is a variable that is associated (read attached) with the object itself, i.e. the properties have a name and value is one of the attributes linked with the property, which defines the access granted to the property. You can access a property of an object using the dot (.) notation or bracket ([]) notation. For instance, the key is a property of the obj object, and the value of the property is accessed using both, dot notation as well as bracket notation.

var obj = {"key": "value"}
console.log(obj.key) // dot notation
console.log(obj["key"]) // bracket notation

Output:

value
value

Here, we will understand how to access the response of a promise object. A Promise is a javascript object that returns upon completion of an asynchronous operation. A Promise has 3 states:

  • Fulfilled: When an asynchronous operation completes without throwing any errors.
  • Rejected: When an asynchronous operation could not complete and throws an error midway.
  • Pending: When an asynchronous operation is ongoing.

Now, to understand how to access a javascript object’s properties when the object is a response to a promise, let’s look at the below approaches.

Approach 1: Using async/await syntax to handle promise-based behavior

Async/Await helps in writing cleaner code for handling promises. The async keyword is used with functions that handle asynchronous operations, and the await keyword is used in an async function, that awaits the response of an asynchronous operation, for example, a promise.

Example: This example describes the process for accessing the object’s properties in Javascript.

Javascript




<script>
    // A function that returns a promise object
    const call = (input) => {
        return new Promise((resolve, reject) => {
            return resolve({
                val: input
            })
        })
    }
     
    // Let’s await the response of the promise
    // and log the result to the console
    async function test() {
        const res = await call("Hello World!")
        console.log(res.val); // dot notation
        console.log(res["val"]) // bracket notation  
    }
    test();
</script>


If you do not wish to use the await keyword to await the Promise response, then you can also choose to go for the Promise chaining technique using the then keyword to wait for a promise response before proceeding ahead in a callback chain.

Output:

Hello World!
Hello World!

Approach 2: Using the ‘then’ keyword to implement a promise chain

The then() method handles the response of promise, be the state of the promise is either fulfilled or rejected. It takes two callback functions, one for each of the above-mentioned promise states. 

Example: This example describes the process for accessing the object’s properties in Javascript by using the ‘then‘ keyword to implement a promise chain.

Javascript




<script>
    // A function that returns a promise object
    const call = (input) => {
      return new Promise((resolve, reject) => {
        return resolve({
          val: input,
        });
      });
    };
     
    // Use then keyword to wait for the response
    // and use a callback function to log the
    // result to the console
     
    // Dot notation
    call("Hello World!")
      .then((res) => console.log(res.val));
     
    // Bracket notation
    call("Hello World!")
      .then((res) => console.log(res["val"]));
</script>


Output:

Hello World!
Hello World!

RELATED ARTICLES

Most Popular

Recent Comments