Brandon
Brandon

Reputation: 159

How to wait for .map() to finish and generate new keys in the array[index]

I'm trying to generate an array with values as follows:

{ name: 'John', age: 35, employer: 'ABC', paycheck: 5,000, last_paycheck: 4,900, change: 100 } // new array

with the initial values in the array as follow:

{ name: 'John', age: 35, employer: 'ABC' } //inital array

the function convertData() is handling all the array conversion.

async function convertData(data){
    if(data.length === 0) return data;
    // generates new array
    const convertedDataArray = await data.map( async (row) =>{
        let name = row.name
        let paycheck = 0;
        let last_paycheck = 0;
        let change = 0;

        const response = await axios.get('/getData', {params: {
            name,
        }});
        let apiData = response.data.data;
        if(apiData.length > 0){
            let newData = apiData[0];
            let oldData = apiData[1];

            change = newData.payCheck - oldData.payCheck;
            paycheck = newData.payCheck;
            last_paycheck = oldData.payCheck;
        }
        console.log(apiData); // prints records up to 100 elements
        return {...row, paycheck, last_paycheck, change };
    });
    console.log(convertedDataArray);// prints [Promise]
    return Promise.all(convertedDataArray).then(() =>{
        console.log(convertedDataArray); // prints [Promise]
        return convertedDataArray;
    });
};

where convertData() is called:

const response = await axios.get('/getEmployees',{params: {
  token: id,
}});
const dataRows = response.data; //inital array
const tableRows = await convertData(dataRows);
return Promise.all(tableRows).then(() =>{
  console.log(tableRows); // prints [Promise]
  dispatch(setTableRows(tableRows));
});

I'm not sure why i keep getting Promise return I am still learning how to use promise correctly. Any help would be great, thank you in advance!

Upvotes: 1

Views: 996

Answers (1)

ikhvjs
ikhvjs

Reputation: 5947

You should get a array of promises and use Promises.all to get all the data first. Then use map() function to construct your data structure.

Example below:

async function convertData(data) {
  try {
    if (data.length === 0) return data;

    const arrayOfPromises = data.map(row =>
      axios.get("/getData", {
        params: {
          name: row.name,
        },
      })
    );

    const arrayOfData = await Promise.all(arrayOfPromises);

    const convertedDataArray = arrayOfData.map((response, i) => {
      const apiData = response.data.data;
      let paycheck = 0;
      let last_paycheck = 0;
      let change = 0;

      if (apiData.length > 0) {
        const newData = apiData[0];
        const oldData = apiData[1];
        change = newData.payCheck - oldData.payCheck;
        paycheck = newData.payCheck;
        last_paycheck = oldData.payCheck;
      }
      return { ...data[i], paycheck, last_paycheck, change };
    });

    return convertedDataArray;
  } catch (err) {
    throw new Error(err);
  }
}

(async function run() {
  try {
    const response = await axios.get("/getEmployees", {
      params: {
        token: id,
      },
    });

    const dataRows = response.data;

    const tableRows = await convertData(dataRows);

    dispatch(setTableRows(tableRows));
  } catch (err) {
    console.log(err);
  }
})();

Upvotes: 1

Related Questions