0

I'm refactoring some old code and would appreciate some help on this, I think It's most likely a misunderstanding of async/await and ES6 modules on my part.

I have two files; Utils.js:

import { displayInfo } from './DisplayInfo';

const someApi = "https://....";

const apiPromise = async (string) => {
  let response = await fetch(someApi + string);
  let json = await response.json();

  return json;
}

const getFooBarInformation = () => {
  const promiseAll = Promise.all([apiPromise('foo'), apiPromise('bar')]);

  const array = [];
  const dictionary = {};

  promiseAll
    .then(response => {
      /* Populate array and dictionary, then merge into one array 'mergedInformation' */

      displayInformation(mergedInformation);
    })
    .catch(errors => {
      /* Handle Errors */
    })
}

export { getFooBarInformation }

And Main.js:

import { getFooBarInformation } from './Utils';

getFooBarInformation();

Ideally, I would like to be able to return mergedInformation to main.js which can then call displayInformation() as I feel like this is far more readable. Like below:

import { getFooBarInformation } from './Utils';
import { displayInfo } from './DisplayInfo';

const mergedInformation = getFooBarInformation();
displayInformation(mergedInformation);

I think that means I would have to update getFooBarInformation to an async function as well but I am not sure how I would return mergedInformation array if that is the case.

const mergedInformation = await getFooBarInformation();
displayInformation(mergedInformation);
qww
  • 7
  • 5

1 Answers1

1

try:

const getFooBarInformation = async () => {
  const response = await Promise.all([apiPromise('foo'), apiPromise('bar')])
  /* Populate array and dictionary, then merge into one array 'mergedInformation' */
  return mergedInformation;
}

and then:

try {
  const mergedInformation = await getFooBarInformation();
  displayInformation(mergedInformation);
} catch(errors) {
  /* Handle Errors */
}

but this last part has to be inside of an async function, otherwise you can do:

getFooBarInformation()
  .then(mergedInform => displayInformation(mergedInformation))
  .catch(errors => /* handle errors */ )
André Alçada Padez
  • 10,987
  • 24
  • 67
  • 120
  • So I was considering this as it does work, but does this not negate the point of having the catch method? If there are issues there will still be an 'undefined' error when I get to the "Populate array and dictionary etc." part. Thank you for your message – qww Sep 22 '22 at 17:58
  • Nevermind, putting it inside a then does indeed still work. Thanks again. – qww Sep 22 '22 at 18:11
  • You probably [don't want to catch errors *inside* the function](https://stackoverflow.com/q/50896442/1048572) – Bergi Sep 22 '22 at 21:16
  • true, i'll make an edit – André Alçada Padez Sep 22 '22 at 22:12