{returnnewPromise((resolve,"/> {returnnewPromise((resolve,">

Home  >  Article  >  Web Front-end  >  How to access object properties from the result returned by async() function in JavaScript?

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

PHPz
PHPzforward
2023-08-25 08:13:10748browse

如何从 JavaScript 中 async() 函数返回的结果访问对象属性?

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

Example 1

In this example, let us understand how to access object properties 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();

illustrate

  • Step 1 - Define a function "promiseFunction" that returns a Promise.

  • Step 2 - Define an asynchronous function "test" to access the properties of the object using dot notation.

  • Step 3 - Display the results.

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();

illustrate

  • Step 1 - Define a function "promiseFunction" that returns a Promise.

  • Step 2 - Define an asynchronous function "test" to access the properties of the object using bracket notation.

  • Step 3 - Display the results.

The above is the detailed content of How to access object properties from the result returned by async() function in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete