0

I have some code that uses Async / Await and works fine...Here is the code:

async function main() {
  const x = await myfunction();
  return x;
}

I wanted to do something like this:

async function main2() {
  const x = await myfunction();
  const x2 = await myfunction2();
  return x;
  return x2;
}

My issue is that the above code doesn't allow more that one return.

So my question is... Is there a way to have multiple returns working on main2() ?

  • 2
    Possible duplicate of [Return multiple values in JavaScript?](https://stackoverflow.com/questions/2917175/return-multiple-values-in-javascript) – chazsolo May 06 '19 at 14:16
  • Depending on your use cases, you could also use [generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*). – Pedro Corso May 06 '19 at 14:24

2 Answers2

3

return as array or object

async function main2() {
  const x = await myfunction();
  const x2 = await myfunction2();
  return [x, x2]
  // or
  return {f1: x, f2: x2}
}

main2()
  .then(res => console.log(res))
  .catch(err => console.log(err))
  • Just in case if someone is confused on whether returning an array nor an object - go for an object cause labeling of the values in an object makes it easy to maintain i.e; accessing required data from objects is more convenient. – whoami - fakeFaceTrueSoul May 06 '19 at 15:03
0
return {
 x,
 x2
}

Then access property main2().x or main2().x2.

Adam Orłowski
  • 4,268
  • 24
  • 33