RoktSe
RoktSe

Reputation: 469

Avoid calling functions multiple times ReactJs

So basically I have a function called calculations() that is doing some calculations and returning some objects.

The problem is that in a component, I need to call this function several times to get the objects it returns and it ends up generating a delay in the code. Like that:

const myTest1 = this.calculations().value1;
const myTest2 = this.calculations().value2;
const myTest3 = this.calculations().value3;

console.log(myTest1, myTest2, myTest3)

Is there any way to do this without having to call the function multiple times? I'm using class components so I can't use the hooks from the new version of react.

Upvotes: 0

Views: 213

Answers (2)

Andy
Andy

Reputation: 63524

If the calculcations are taking time but you need to log all the results together you may want to looking to wrapping each result in a promise and returning that. This way you then use Promise.all to wait for all the calculations to complete (or fail) before dealing with them.

Here's a short demonstration.

// Calculation returns a promise
// In this example it waits for
// `n` seconds and then returns `n` times 10
// but the `setTimeout` can be whatever your calculation is
function calculation(n) {
  return new Promise((res, rej) => {
    setTimeout(() => res(n * 10), n * 1000);
  });
}

// Example array of calculations required
const calcsNeeded = [1, 2, 3];

async function doCalcs() {

  // `map` over the array and return the promise
  // for each calculation
  const promises = calcsNeeded.map(calculation);

  // Wait for them to all resolve (or be rejected)
  const results = await Promise.all(promises);

  // Log the results
  // Note that "Logged first" gets logged first
  console.log(results);
}

doCalcs();
console.log('Logged first');

Upvotes: 0

Quentin
Quentin

Reputation: 943157

In general, if you want to do multiple things with the result of an expression then store the result of the expression in a variable.

const myResults = this.calculations();
const myTest1 = myResults.value1;
const myTest2 = myResults.value2;
const myTest3 = myResults.value3;

console.log(myTest1, myTest2, myTest3)

That said, in the specific case where the "multiple things" are "store property values in variables" you could also use a destructuring operation:

const { value1: myTest1, value2: myTest2, value3: myTest3 } = this.calculations();

Upvotes: 3

Related Questions