AbreQueVoy
AbreQueVoy

Reputation: 2316

TypeError: Cannot read properties of undefined (reading 'id') during async calls inside a Promise

In this piece of code, there is data coming from different sources, and it arrives with different delays. That's why I'm using asynchronous calls, but apparently I'm doing something wrong:

const handleCalculations = async ({
    configuration,
    product,
}) => {
    const configurations = [];
    const results = {};
    
    /*
    configurations get populated with elements
    */
    
    await Promise.all(configurations.map(async (configuration) => {
        const calcResult = await getResults(configuration);
        
        if (calcResult.message !== 'OK') {
            console.error('Error occurred');
        }
        
        const builtResponse = await getResponse(configuration)
            .filter(populatedOnly);
            
        console.log({ result });  // error gets thrown among logged result 
        
        const resKey = processed.config.module;
        results[resKey] = {};   // initialize property
        results[resKey].respId = await calcResult.result.configuration.id;  // error relates to this line
        results[resKey].result = builtResponse;
    }));
    
    return {
        message: 'OK',
        result: results,
    };
};

The error that gets displayed is something like:

TypeError: Cannot read properties of undefined (reading 'id')

How to make sure the data is in place when it's time to read it?

Upvotes: 0

Views: 1111

Answers (1)

minhazmiraz
minhazmiraz

Reputation: 452

You have to return an array of Promises to Promise.all() function. But in your code you are not returning anything. I am just giving an example similar to your code below.

const configurations = ['https://jsonplaceholder.typicode.com/todos/1', 'https://jsonplaceholder.typicode.com/todos/2'];
const results = {};

let ret = (async function run() {
    let calcResult = await Promise.all(
    configurations.map(
      (configuration) => fetch(configuration)
    )
  );
  
  calcResult = await Promise.all(
    calcResult.map(
      (i) => i.json()
    )
  );
  
  calcResult.map(res => {
    results[res.id] = res.title;
  });
  
  console.log(results);

})();

Here, fetch() and json() return Promise to Promise.all() function. Promise.all() executed after all the Promises properly resolved. You can check more about it here.

Upvotes: 1

Related Questions