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

如何调整异步调用顺序确保POST请求的options.body不为undefined

核心问题原因

  1. roles.js 存在两个错误:
    • getRoles 是异步函数但没有返回 Promise,外部无法等待内部 fetch 执行完成
    • setEnviroment 最后错误返回了未定义的 req 变量,应该返回构造好的请求体 reqBody
  2. config.js 中调用 rolesJson(env) 时没有等待异步结果返回就直接序列化,自然得到 undefined

修复后的代码

第一步:修改 roles.js

var roleUrl = 'www.example.com/roles';

const setEnviroment = (rolesdata,env) => {
  let reqBody = {
    "environment": env,
    "components": rolesdata
  }
  console.log("REQUEST BODY CREATED", reqBody);
  // 修复:返回构造好的reqBody而非未定义的req
  return reqBody;
}

// 修复:返回Promise,外部可以await等待结果
const getRoles = async (env) => {
  try {
    const response = await fetch(roleUrl);
    const roles = await response.json();
    let rolesList = roles.map(x => ({
      name: x.name,
      id: x.id,
    }))
    return setEnviroment(rolesList, env);
  } catch (error) {
    console.error('获取角色失败', error);
    throw error;
  }
};
module.exports = getRoles;

第二步:修改 config.js

构造函数本身不支持异步操作,建议将初始化逻辑抽为独立的异步方法,或者使用静态工厂方法创建实例:

import rolesJson from '../../roles';

class Config{
  url;
  rolesList;

  // 不要在构造函数内执行异步逻辑,改为静态工厂方法创建实例
  static async init() {
    const config = new Config();
    var baseurl = 'www.example.com/env';
    try {
      const envRes = await fetch(baseurl);
      const envData = await envRes.json();
      config.url = envData.url;
      // 等待getRoles返回结果后再构造请求
      const authBody = await rolesJson(envData.env);
      await config.getAuth(authBody);
      return config;
    } catch (error) {
      console.error('初始化Config失败', error);
      throw error;
    }
  }

  async getAuth(authBody) {
    const headers = { 'Content-Type': 'application/json' };
    const options = { 
      method: 'POST', 
      headers, 
      body: JSON.stringify(authBody)
    };
    console.log("THIS BODY SHOULD NOT BE UNDEFINED", options.body);
    try {
      const authRes = await fetch('www.example.com/auth', options);
      const authData = await authRes.json();
      // 后续处理authData的逻辑写在这里
      return authData;
    } catch (error) {
      console.error('认证请求失败', error);
      throw error;
    }
  }
}
module.exports = Config;

使用方式

创建Config实例时调用静态init方法即可保证执行顺序:

// 异步上下文内调用
const config = await Config.init();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:36:09