How to access object properties from result returned by async() function in JavaScript ?
Last Updated :
09 Jan, 2023
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!
Similar Reads
How to Store an Object sent by a Function in JavaScript ? When a function in JavaScript returns an object, there are several ways to store this returned object for later use. These objects can be stored in variables, array elements, or properties of other objects. Essentially, any data structure capable of holding values can store the returned object. Tabl
2 min read
How to get dynamic access to an object property in JavaScript ? In JavaScript, an object is a collection of properties, where each property consists of a key-value pair. Objects are a fundamental data type in JavaScript. You can create an object in JavaScript in the following ways: By using the object literal notation, which is a comma-separated list of key-valu
7 min read
How to Traverse Array of Objects and Access the Properties in JavaScript? Here are the various methods to traverse an array of objects and access the properties in JavaScript1. Using forâ¦in loopThe for...in loop is used to iterate over the enumerable properties of an object. JavaScriptconst a = [ {name: 'Saritha', sub: 'Maths'}, {name: 'Sarthak', sub: 'Science'}, {name: '
4 min read
How a Function Returns an Object in JavaScript ? JavaScript Functions are versatile constructs that can return various values, including objects. Returning objects from functions is a common practice, especially when you want to encapsulate data and behavior into a single entity. In this article, we will see how a function returns an object in Jav
3 min read
How to convert an asynchronous function to return a promise in JavaScript ? In this article, we will learn how to convert an asynchronous function to return a promise in JavaScript. Approach:Â You need to first declare a simple function (either a normal function or an arrow function (which is preferred)). You need to create an asynchronous function and then further you need
3 min read
How to read properties of an Object in JavaScript ? Objects in JavaScript, it is the most important data type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScriptâs primitive data-types(Number, String, Boolean, null, undefined, and symbol) in the sense that these primitive data-types all store a singl
2 min read
How to use await outside of an async function in JavaScript ? In this article, we will try to understand in what way or by how we may use await outside of an async function in JavaScript with the help of both theoretical explanations as well as coding examples. Let us first understand the following shown section in which all the syntaxes of declaring a promise
4 min read
How to print the content of an object in JavaScript ? To print the content of an object in JavaScript we will use JavaScript methods like stringify, object.values and loops to display the required data. Let's first create a JavaScript Object containing some key-values as given below: JavaScript // Given Object const obj = { name: 'John', age: 30, city:
3 min read
How To Return the Response From an Asynchronous Call in JavaScript? To return the response from an asynchronous call in JavaScript, it's important to understand how JavaScript handles asynchronous operations like fetching data, reading files, or executing time-based actions. JavaScript is a single-threaded nature means it can only handle one task at a time, but it u
3 min read
How to Return an Array from Async Function in Node.js ? Asynchronous programming in Node.js is fundamental for handling operations like network requests, file I/O, and database queries without blocking the main thread. One common requirement is to perform multiple asynchronous operations and return their results as an array. This article explores how to
4 min read