You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于async/await重构代码,实现Utils向Main.js返回数据

代码重构方案

第一步:修改 Utils.js

移除不必要的导入,将 getFooBarInformation 改为 async 函数,直接返回处理后的 mergedInformation:

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

const apiPromise = async (string) => {
  const response = await fetch(someApi + string);
  // 新增:检查请求是否成功,避免解析错误响应
  if (!response.ok) {
    throw new Error(`请求失败,状态码:${response.status}`);
  }
  const json = await response.json();
  return json;
};

const getFooBarInformation = async () => {
  // 等待两个API请求完成,解构获取各自返回数据
  const [fooData, barData] = await Promise.all([
    apiPromise('foo'),
    apiPromise('bar')
  ]);

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

  // 保留你的原逻辑:填充array和dictionary,生成mergedInformation
  // 示例逻辑(请替换为实际业务代码):
  array.push(...fooData.list);
  dictionary.barMeta = barData.metadata;
  const mergedInformation = [...array, dictionary.barMeta];

  // 返回处理后的结果
  return mergedInformation;
};

export { getFooBarInformation };

第二步:修改 Main.js

由于 getFooBarInformation 是 async 函数,调用时需要用 await(需在 async 上下文内)或 .then() 获取结果,同时统一错误处理:

方案一:使用 async/await(推荐,可读性更强)

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

// 用立即执行async函数包裹,适配多数环境的顶层代码限制
(async () => {
  try {
    const mergedInformation = await getFooBarInformation();
    displayInfo(mergedInformation);
  } catch (error) {
    // 统一处理错误,比如打印日志或提示用户
    console.error('获取合并信息失败:', error);
  }
})();

方案二:使用 .then()/.catch()

如果偏好回调风格,也可以这样写:

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

getFooBarInformation()
  .then(mergedInformation => displayInfo(mergedInformation))
  .catch(error => console.error('获取合并信息失败:', error));

关键说明

  1. async 函数的返回特性:async 函数默认返回 Promise,必须通过 await 或 .then() 才能拿到实际返回值,你之前猜测的 await getFooBarInformation() 是正确用法。
  2. 单一职责优化:Utils.js 不再导入 displayInfo,专注于数据获取和处理,UI 展示逻辑交给 Main.js,代码职责更清晰。
  3. 错误处理升级:在 apiPromise 中新增 HTTP 状态检查,避免解析失败响应;错误统一在调用层处理,让调用者拥有更灵活的错误处理权限。
  4. 代码简化:用 const [fooData, barData] = await Promise.all(...) 直接获取两个 API 的返回结果,比原 .then(response => ...) 写法更直观线性。

内容的提问来源于stack exchange,提问作者qww

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 14:25:25