Home > Enterprise >  Returning array inside promise success
Returning array inside promise success

Time:09-23

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

I think that Utils.js handles too much inside of the then(). 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);

CodePudding user response:

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 */ )
  • Related