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

Node.js未处理Promise拒绝问题及模块变量传递修正求助

解决Binance US API数据拉取模块的Promise未处理及变量传递问题

问题背景

开发了一个从Binance US API拉取数据的模块,但无法将变量正确传递至其他文件。希望实现一个函数,每次运行时拉取变量并将其作为动态变量供其他文件使用,但遇到了未处理Promise拒绝的错误。

原代码

/modules/Tradepair.js

async function getTradepair() {
  const apiUrl = "https://api.binance.us/api/v3/ticker/24hr";
  // Make a GET request
 let data ;
 try{
    const response = await fetch(apiUrl);
    if (!response.ok) {
       throw new Error("Network response for pair was not ok");
    }
     data = await response.json();
    //  console.log(data);

 } catch (error) {
     console.error('There was a problem with the fetch operation:', error);
}
  const max = data.reduce(
      (a, b) => (a.priceChangePercent > b.priceChangePercent ? a : b), data[0]);
  console.log(`Max Symbol from API: ${max.symbol}`);
  console.log(`Max Percent from API: ${max.priceChangePercent}`);
  const tradingPair = max.symbol;
  console.log(`Assigned to Trading pair variable: ${tradingPair}`);
  return tradingPair; // Return the tradingPair variable
}
module.exports = getTradepair;

主文件

require("dotenv").config();
const Wolf = require("./modules/Wolf.js");
const getTradepair = require("./modules/Tradepair.js"); //file-name where you have defined this `getTradepair()` function.

async function getData() {
  try {
    const data = await getTradepair();
    console.log("From index:" + " " +data);
    return data;
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

const config = {
  // tradingPair: process.env.TARGET_ASSET + process.env.BASE_ASSET,
  tradingPair: getData(),
  profitPercentage: Number(process.env.PROFIT_PERCENTAGE) / 100,
  budget: Number(process.env.BUDGET),
  compound: process.env.COMPOUND.toLowerCase() === "true",
  profitLockPercentage: Number(process.env.PROFIT_LOCK_PERCENTAGE) / 100,
  stopLimitPercentage: Number(process.env.STOP_LIMIT_PERCENTAGE) / 100,
};

const wolf = new Wolf(config);

错误信息

Max Symbol from API: VITEUSDT
Max Percent from API: 6.467
Assigned to Trading pair variable: VITEUSDT
From index: VITEUSDT
node:internal/process/promises:289
            triggerUncaughtException(err, true /* fromPromise */);
            ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "false".] {
  code: 'ERR_UNHANDLED_REJECTION'
}

Node.js v20.12.1
[nodemon] app crashed - waiting for file changes before starting...

错误原因分析

  1. tradingPair被赋值为Promise而非实际值:getData()是异步函数,直接赋值给config.tradingPair会导致该字段是未resolved的Promise,而非预期的交易对字符串。若Wolf类构造函数无法处理Promise类型参数,会引发后续错误。
  2. 异步流程未正确处理:主文件未等待getData()完成就直接实例化Wolf,导致依赖异步数据的逻辑提前执行;同时getTradepair中仅处理了fetch错误,后续reduce操作若遇到data为undefined的情况,会抛出未被捕获的错误,引发Promise拒绝。

修正方案

步骤1:修复getTradepair的错误处理

确保fetch失败或数据异常时,函数能正确处理并传递错误:

async function getTradepair() {
  const apiUrl = "https://api.binance.us/api/v3/ticker/24hr";
  let data;
  try {
    const response = await fetch(apiUrl);
    if (!response.ok) {
      throw new Error("Network response for pair was not ok");
    }
    data = await response.json();
    // 校验返回数据格式
    if (!Array.isArray(data) || data.length === 0) {
      throw new Error("Invalid data received from API");
    }
  } catch (error) {
    console.error('There was a problem with the fetch operation:', error);
    throw error; // 重新抛出错误,让上层统一处理
  }
  const max = data.reduce(
    (a, b) => (a.priceChangePercent > b.priceChangePercent ? a : b), data[0]);
  console.log(`Max Symbol from API: ${max.symbol}`);
  console.log(`Max Percent from API: ${max.priceChangePercent}`);
  const tradingPair = max.symbol;
  console.log(`Assigned to Trading pair variable: ${tradingPair}`);
  return tradingPair;
}
module.exports = getTradepair;

步骤2:重构主文件的异步流程

用async/await确保获取到交易对数据后再实例化Wolf:

require("dotenv").config();
const Wolf = require("./modules/Wolf.js");
const getTradepair = require("./modules/Tradepair.js");

// 封装主逻辑为异步函数
async function main() {
  try {
    const tradingPair = await getTradepair();
    console.log("From index:" + " " + tradingPair);

    const config = {
      tradingPair,
      profitPercentage: Number(process.env.PROFIT_PERCENTAGE) / 100,
      budget: Number(process.env.BUDGET),
      compound: process.env.COMPOUND.toLowerCase() === "true",
      profitLockPercentage: Number(process.env.PROFIT_LOCK_PERCENTAGE) / 100,
      stopLimitPercentage: Number(process.env.STOP_LIMIT_PERCENTAGE) / 100,
    };

    const wolf = new Wolf(config);
    // 可在此添加wolf实例的后续逻辑
  } catch (error) {
    console.error("Error initializing application:", error);
    process.exit(1); // 异常退出进程
  }
}

// 执行主函数
main();

修正说明

  • 将主逻辑包裹在main异步函数中,确保所有依赖异步数据的操作等待Promise完成后再执行。
  • 完善getTradepair的错误处理:添加返回数据格式校验,catch块重新抛出错误让上层统一处理。
  • 直接用await getTradepair()获取交易对字符串,避免将Promise赋值给config.tradingPair。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 00:12:21