0

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.

1
  • 2
    "I can't use the hooks from the new version of react." — Hooks were introduced in React 16.8 which was released on 6 February 2019. Wikipedia lists 12 releases of React since then. They're hardly new any more. Commented Aug 26, 2021 at 13:31

2 Answers 2

3

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.