I am searching for a way to retrieve the output of an asynchronous function within an Object

Currently, I am facing an issue with my async function where the value of the properties in the object is turning into an Object Promise instead of the desired result. Below is a snippet of my code:

const promise1 = new Promise(function(resolve, reject) {
  resolve('myvalue');
});
const a = async () => {
  var b = await promise1
  return b;
}
const newobj = {'a': a()};

console.log(newobj)

// The output shows: {a: Promise {<resolved>: "myvalue"}} but I wish to see {a: "myvalue"}

Answer №1

There seems to be an issue in your code where you are assigning the result of a (which is an asynchronous function, thus returning a Promise) to newObj.a

An asynchronous function can include an await expression that halts the execution of the asynchronous function until the Promise it awaits resolves, and then continues with the function's execution, returning the resolved value. For more details, you can refer to this link: here

Keep in mind that the await keyword is only valid within async functions. If used outside of an async function body, it will lead to a SyntaxError.

Approach 1

const promise1 = new Promise(function(resolve, reject) {
  resolve('myvalue');
});
const a = async() => {
  var b = await promise1
  return b;
}

const printData = async() => {
  const newobj = {
    'a': await a()
  };
  console.log(newobj)
}

printData()

EDIT: Upon johnson andriatiana's request, I have enclosed the code within an async IIFE function.

Approach 2:

(async() => {
  const promise1 = new Promise(function(resolve, reject) {
    resolve('myvalue');
  });
  const a = async() => {
    var b = await promise1
    return b;
  }
  const newobj = {
    'a': await a()
  };

  console.log(newobj)
})();

Answer №2

When calling a(), the issue arises because it returns a promise. Therefore, to properly assign the result of the promise, you must wait for it to complete first.

One potential solution is outlined below:

const promise1 = new Promise(function(resolve, reject) {
  resolve('myvalue');
});
const a = async () => {
  var b = await promise1
  return b;
}
const run = async () => {
  const newobj = {'a': await a()};
  console.log(newobj);
}

run()
   

Answer №3

Make sure to use the await keyword with your async function. Instead of:

const newobj = {'a': a()};

try this:

const newobj = {'a': await a()};

The function a() returns a promise, and await a() will be the resolved value of that promise.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Styling Bootstrap radio toggle buttons using CSS

I am currently utilizing Bootstrap version 3.37 and have implemented two toggle buttons for users to select from. My goal is to have the "active" state assigned to the blue button when clicked, displaying a dark color. Conversely, when the green button is ...

unique map customized in a separate browser window

Attempting to complete the code provided here but encountering issues as a novice in java-scripting. It seems like the map is not loading correctly. A new tab and text are generated when DIV is created. Seeking assistance on how to open a custom map in a ...

What is the best way to ensure that JavaScript only impacts a specific element?

Looking for a simple JavaScript solution that toggles the "open" class on a specific element? I'm currently facing an issue where all elements with the classes .clickSlide and .sub_menu get the "open" class when any one of them is clicked. What I real ...

The function template.rendered in Meteor is invoked before the content on the page is fully displayed

When my page is rendered, I am attempting to incorporate autocomplete functionality into an input field. Template.friends.rendered = function () { var users = Meteor.users.find({}).fetch(); // Obtain all usernames from the local minimongo var ...

Having trouble with the CKEditor character count function in JavaScript?

I integrated the Javascript and stylesheet from this source into my webpage. http://jsfiddle.net/VagrantRadio/2Jzpr/ However, the character countdown is not appearing on my site. What mistake have I made? ...

"Fill out the form fields by selecting a row option from the dropdown menu in response

Here is my working example of retrieving addresses associated with the current user who is logged in. The mysqli query is successfully printing the options for addresses stored in the mysql database, which are linked to the session username. Addresses are ...

"Efficiently calculate the total sum of columns in a datatable using dynamic JavaScript across

For further clarification, this question is an extension of a previous inquiry, which can be viewed here. In the following code snippet, I am calculating the column sum of a Shiny datatable using Javascript in order to display it directly below the table. ...

Guidance on Applying Texture to a Targeted Area of a 3D Model in Three.js

Currently immersed in a Three.js project, I find myself faced with the challenge of projecting a texture onto a particular surface of a 3D model. Despite loading the model through GLTFLoader and possessing the necessary texture, my attempts at using Raycas ...

Node.js and socket.io come together in this collaborative text editing tool

I'm currently working on a collaborative app utilizing node and sockets that includes a simple text tool feature. My goal is for any user who types and applies text to the canvas to have that text visible to all other connected users. Here's wha ...

Invalid Operation: The value 'undefined' cannot be used as a function

I've been working on implementing a date picker feature for an HTML form. In the HTML header, I have included the following script: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> The script I&apo ...

Executing React's useEffect hook twice

As I work on developing an API using express.js, I have implemented an authentication system utilizing JWT tokens for generating refresh and access tokens. During testing with Jest, Supertest, and Postman, everything appears to be functioning correctly. O ...

jQuery not working: Trouble with $.load function

Currently implementing jQuery on my Django website to refresh a specific div when a user clicks a button. $(document).ready(function(){ var post_list = Array.from(document.getElementsByClassName("post_container")) for(var post in post_lis ...

How to use Vanilla JavaScript to toggle a click event on a list item (LI) that

I have a script that scans through a webpage and identifies a unique string, for example: multus –a –um. The page contains several <LI> elements with various text content, including instances of multus –a –um. I need a solution to locate an & ...

Difficulty with Ajax post function in CodeIgniter

I am currently working with CodeIgniter version 3.1. When attempting to use Ajax post, I encountered a 403 (Forbidden) error in the console. [POST http://localhost/test/post 403 (Forbidden)] HTML <div class="post"> <input type ...

Utilizing Flask to gather information from a leaflet map

I am currently working on creating a webpage using Flask. The webpage features a leaflet map where users can click to create a marker that opens a popup window with a link. The link's purpose is to open a new page displaying the longitude and latitude ...

What is the best way to combine two arrays while ensuring the elements of the second array appear before the elements of the first

Is there a way to concatenate two arrays in JavaScript, where the second array appears before the first? For example: const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const combinedArr = arr1.concat(arr2); console.log(combinedArr); I am aware that yo ...

Assessing special characters in JavaScript string literals

Let's examine the code below: var a = '\\555'; var b = '\555'; console.log(a, b); // outputs \555 -5 In this code snippet, variable a contains an escaped back-slash, while variable b has an escaped character w ...

The Vue.js 3 input field remains unchanged even after updating the value in the watch hook

I recently implemented a TextInput component and followed the instructions in the Vue documentation by adding the v-model directive to my component. Here is the code snippet of my component: <template> <div class="floating_input"> ...

Verification of content pages through Jquery

In my master page, I have created a placeholder like: <asp:ContentPlaceHolder ID="MasterContentPlaceHolder" runat="server"> </asp:ContentPlaceHolder> The content pages inherit this master page. Within the content page, I've added a < ...

Unable to designate a default boolean parameter as default

I've been exploring various methods for setting default parameters for jQuery functions. One approach I found interesting involves creating a JSON object within the function and utilizing extend to combine any provided options. Currently, however, I h ...