【问题标题】:Returning array inside promise success在承诺成功中返回数组
【发布时间】:2022-09-23 06:13:46
【问题描述】:

我正在重构一些旧代码并希望得到一些帮助,我认为这很可能是我对 async/await 和 ES6 模块的误解。

我有两个文件;实用程序.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 }

和 Main.js:

import { getFooBarInformation } from \'./Utils\';

getFooBarInformation();

我认为 Utils.js 在 then() 内部处理的太多了。理想情况下,我希望能够将 mergeInformation 返回给 main.js,然后它可以调用 displayInformation(),因为我觉得这更具可读性。如下所示:

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

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

我认为这意味着我也必须将 getFooBarInformation 更新为异步函数,但我不确定如果是这种情况我将如何返回 mergeInformation 数组。

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

    标签: javascript async-await es6-modules


    【解决方案1】:

    尝试:

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

    接着:

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

    但是最后一部分必须在异步函数中,否则你可以这样做:

    getFooBarInformation()
      .then(mergedInform => displayInformation(mergedInformation))
      .catch(errors => /* handle errors */ )
    

    【讨论】:

    • 所以我正在考虑这个,因为它确实有效,但这是否否定了使用 catch 方法的意义?如果有问题,当我进入“填充数组和字典等”时,仍然会出现“未定义”错误。部分。感谢您的留言
    • 没关系,把它放在 then 里面确实仍然有效。再次感谢。
    • 是的,我会进行编辑
    猜你喜欢
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    相关资源
    最近更新 更多