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


In this article, you will understand how to access object properties from result returned by async() functions in JavaScript. An object property in JavaScript is a variable that is associated with the object itself, i.e. the properties have a name and value is one of the attributes linked with the property.

Example 1

In this example, let’s understand how to access objects property using dot notation

console.log("A function is created that returns promise object")
const promiseFunction = (input) => {
   return new Promise((resolve, reject) => {
      return resolve({
         val: input
      })
   })
}

console.log("
Calling the function using dot notation") async function test() { const result = await promiseFunction("This is an asynchronous function response") console.log(result.val); } test();

Explanation

  • Step 1 − Define a function ‘promiseFunction’ that returns a promise.

  • Step 2 − Define an async function ‘test’ that accesses the property of the object using dot notation.

  • Step 3 − Display the result.

Example 2

In this example,

console.log("A function is created that returns promise object")
const promiseFunction = (input) => {
   return new Promise((resolve, reject) => {
      return resolve({
         val: input
      })
   })
}

console.log("
Calling the function using bracket notation") async function test() { const result = await promiseFunction("This is an asynchronous function response") console.log(result["val"]) } test();

Explanation

  • Step 1 − Define a function ‘promiseFunction’ that returns a promise.

  • Step 2 − Define an async function ‘test’ that accesses the property of the object using bracket notation.

  • Step 3 − Display the result.

Updated on: 16-Feb-2023

708 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements