What is the best way to assign the result of a promise to a variable?

My code includes an async function that retrieves a value

  async fetchUserName(environment: string, itemName: string, authToken: string): Promise<any> {
      let result = await this.obtainDeviceName(environment, itemName, authToken);
      return result;
  };

In another part of my code, I am invoking the aforementioned function as follows:

let productName;
const prod = this.fetchUserName(environment, itemName, authToken).then((response) => {
    productName = response;
    this.wait(300);
});

Even though the variable `productName` appears to be functioning correctly and displaying the response in my log, when I attempt to use `productName` outside of this particular block, I encounter an issue where it is undefined.

 promoDetails = { 
    name: productName,
    startDate: start,
    endDate: end
 };

I am trying to assign `productName` to the `name` field within the `promoDetails` object, but unfortunately, I cannot seem to get it working as intended.

If anyone could provide insight into what may be causing this issue, I would greatly appreciate it. Thank you.

Answer №1

If you want to set the value of promotion when receiving the response -

const prod = this.getUsername(env,skuName,token).then((resp) => {
    productN =  resp;
    promotion.name = resp
    this.wait(300);
});

As getUsername is an asynchronous function, you can use await to wait for the response before assigning to the promotion object.

(async() => {
  const resp = await this.getUsername(env,skuName,token);
  promotion = {
    name: resp,
    startDate: start,
    endDate: end
  } 
})();

--- Edit ---

const input = [
    {
        env: 'lorem',
        skuname: 'skuname1',
        token: 'dummy'
    }, 
    {
        env: 'lorem',
        skuname: 'skuname2',
        token: 'dummy'
    }
];

const getUserName = (username) => {
    return new Promise(resolve => {
        setTimeout(()=>resolve(username), 2000);
    });
};

(async () => {
    const resp = await Promise.all(input.map(({skuname}) => getUserName(skuname)));
    console.log(resp);
})();

// Or 

Promise.all(input.map(({skuname}) => getUserName(skuname)))
    .then(resp => {
        console.log(resp);
    });

Answer №2

attempt

let item = await this.fetchUserInfo(id,userName,key);
console.log(item);

Answer №3

Could you attempt this approach? Modify your getDeviceName function within the getUsername method;

getUsername(env:string, skuName: string, token:string): Promise<any> {
  return this.getDeviceName(env, skuName, token);
};
const productN = await this.getUsername(env, skuName, token);
console.log(productN);

I am uncertain why you are using the getUsername function when you can directly obtain the value of productN from getDeviceName.

For example

const productN = await this.getDeviceName(env, skuName, token);

If you need to perform any additional tasks within the getUsername method, you can make it return a promise.

getUsername(env:string, skuName: string, token:string): Promise<any> {
 return New Promise(async (resolve,reject)=>{
  try {
   let value =  await this.getDeviceName(env,skuName,token);
   ...
   //all other operations you wish to execute here 
   ...
   resolve(value);
  } catch (error) {
   reject(error)
  }
 }
};

const productN = await this.getUsername(env, skuName, token);
console.log(productN);

Note: I included a try catch block for error handling, feel free to disregard if unnecessary.

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

Update the JSON by replacing any null values with a predefined string

When working with JSON data, I often come across empty values that I need to replace with a default string. var jsonData= [ { "machineNum": "1A", "serialNo": "123", "city": "" }, { "machineNum": "2B", "serialNo": "", "city": "" }, ...

sending a POST request with fetch

When it comes to making AJAX requests, I used to rely on jQuery in the past. However, with the rise of React, there is no longer a need to include the entire jQuery library for this purpose. Instead, it is recommended to use JavaScript's built-in fetc ...

Unable to invoke the jQuery function within CakePHP3

I am having trouble calling the jQuery function mentioned below in my CakePHP3 MVC project. There are no error messages, but nothing seems to be happening. The code is set up so that jQuery gets included automatically. The function I am trying to call sh ...

The NgRx Store encountered an error: Unable to freeze

I am currently developing a basic login application using Angular, NgRx Store, and Firebase. I have implemented a login action that is supposed to log in to Firebase and store the credentials in the store. However, it seems like there is an issue in my imp ...

A technique in JavaScript that allows for assigning object property values using an external variable

I need to clarify my situation with a code example const faultLine = new google.maps.Polyline({ paths: [ new google.maps.LatLng(49.95, -128.1), new google.maps.LatLng(46.26, -126.3), new google.maps.LatLng(40.3, -125.4) ] }); ...

Using D3.js to plot data points on a topojson map's coordinates

Having difficulty converting latitude and longitude coordinates to "cx" and "cy" positions on my SVG map created with d3 and topojson. Despite researching solutions online, I am unable to successfully implement the conversion process. Each time I try to co ...

How to categorize an array of objects based on a specific property while preserving the original object attributes

I have an array of objects with a specific property that I want to group by. My objective is to create a new array where all the objects have the same properties, but with an additional property that combines all the "value" properties into an array. Here ...

Anomaly in Form Validation with Semantic-UI

This time around, I am implementing Semantic-UI with React. In the past, I have successfully utilized Semantic-UI's form and form validation features in various projects without encountering any issues. However, a new problem has arisen, which I will ...

JavaScript Radio Buttons

Below are the different radiobuttons: Apple <input type="radio" id="one" name="apple" data-price="10" value="light"/> Light <input type="radio" id="two" name="apple" data-price="20" value="dark" /> Dark <input type="text" id="appleqty" name ...

What steps are needed to switch colors after a loop has been clicked?

I have a loop setup like this: data: { show: false } .test { hight: 10px; background-color: red; } .test2 { hight: 15px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div v-for="value in da ...

Tips for sending asynchronous data to Google-Charts-Angular

I am currently working on generating a chart using data obtained from an API call. To achieve this, I am utilizing the google-charts-angular package within my HTML: <google-chart [title]="title" [type]="type" [data]="data" ...

Track WordPress Post Views on Click using AJAX

Is there a way to track the number of post views on my WordPress site using AJAX when a button is clicked? Currently, the view count only updates when the page is refreshed. I want to be able to trigger this function with an AJAX call. Here is the code I ...

An issue arises when attempting to execute npm with React JS

I encountered an error after following the setup steps for a react configuration. Can anyone provide assistance? This is the content of the webpack.config.js file: var config = { entry: './main.js', output: { path:'/', ...

Utilizing jQuery DataTable with an AJAX call to retrieve data from a JSON

I am facing an issue while trying to retrieve data from Entity Framework in ASP.NET MVC using a jQuery data table with AJAX. The data is not displaying in the table as expected. I need assistance in identifying the mistake in my approach. Upon executing t ...

Tips for modifying TypeScript class types based on a parent class object property?

As part of a project, I have created two classes: ParentClass childrenClass which extends the ParentClass class Displayed below is the code for my ParentClass: interface ConfSetup<T extends boolean> { enabled: T; permissions: bigint[]; locati ...

Exploring Vue 3.3: Understanding Generics and Dynamic Properties

I'm currently diving into the generics feature in vue 3.3 and I've been pondering about defining the type of an incoming prop based on another prop value. This is my current component structure: export interface OptionProps { id: string | numb ...

The application is resetting when the "$http" method accesses the initial ADAL "protected" URL for the first time

I have created a page inspired by the Angular SPA ADAL sample which can be found here Upon returning from the Microsoft login page and accessing my API secured with AAD, the angular .config() function is called multiple times. This causes issues with upda ...

Steps to activate highlighting for the initial value in a quarterly datepicker

Concerning the quarterPicker feature in the Bootstrap datePicker (SO: how-to-change-bootstrap-datepicker-month-view-to-display-quarters, jsfiddle: jsFiddle): Is there a way to highlight an initial value upon startup? I have tried setting a value in win ...

The JavaScript function getSelection is malfunctioning, whereas getElementById is functioning perfectly

I am encountering a peculiar situation while trying to input text into a textbox using a JavaScript command. The CSS locator does not seem to update the text, whereas the ID locator is able to do so. URL: Below are screenshots of the browser console disp ...

Issue with bundling project arises post upgrading node version from v6.10 to v10.x

My project uses webpack 2 and awesome-typescript-loader for bundling in nodejs. Recently, I upgraded my node version from 6.10 to 10.16. However, after bundling the project, I encountered a Runtime.ImportModuleError: Error: Cannot find module 'config ...