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

动态创建的JavaScript Function未执行无返回,如何修复?

修复动态创建Function调用fs/promises方法无效的问题

问题分析

你的代码无法正常工作主要有三个核心问题:

  1. Function构造函数使用错误:你传入的字符串定义了一个async箭头函数,但Function返回的函数执行后仅返回这个箭头函数,并未执行它,导致实际的文件操作代码根本没运行。
  2. 参数处理逻辑不安全:用replace直接去除数组括号的方式,会在参数包含[/]字符或嵌套数组时破坏参数结构,引发语法错误。
  3. 校验逻辑冗余:收集所有方法名再循环匹配的写法过于繁琐,可直接通过对象属性判断简化。

修复方案

方案一:直接调用传入的方法(推荐)

完全不需要动态创建Function,直接利用传入的方法引用调用即可,这是最简洁、安全且高效的方式:

class Server {
  public async method(method: Function, args: any[]) {
    const fsp = await import("fs/promises");
    // 简化校验:直接判断方法是否属于fs/promises的导出成员
    const isValidMethod = 
      Object.hasOwn(fsp, method.name) || 
      (fsp.default && Object.hasOwn(fsp.default, method.name));

    if (!isValidMethod) {
      throw new Error("Invalid method");
    }

    // 直接调用传入的方法,展开参数数组
    const result = await method(...args);
    console.log(result);
    return result;
  }
}

方案二:修正动态创建Function的写法(如果必须用动态函数)

若你确实需要通过动态创建Function实现,需修正Function的定义,让它直接返回async函数的执行结果,并正确处理参数:

class Server {
  public async method(method: Function, args: any[]) {
    const fsp = await import("fs/promises");
    const isValidMethod = 
      Object.hasOwn(fsp, method.name) || 
      (fsp.default && Object.hasOwn(fsp.default, method.name));

    if (!isValidMethod) {
      throw new Error("Invalid method");
    }

    // 安全处理参数:逐个序列化后拼接,避免破坏参数结构
    const argsStr = args.map(arg => JSON.stringify(arg)).join(',');
    // 让Function创建的函数直接返回async函数的执行结果
    const callMethod = new Function(
      `"use strict"; return (async () => {
        const {${method.name}} = await import("fs/promises");
        return await ${method.name}(${argsStr});
      })()`
    );

    const result = await callMethod();
    console.log(result);
    return result;
  }
}

验证使用

两种方案的使用方式保持不变:

const server = new Server();
// 注意先导入fs/promises
const fsp = await import("fs/promises");
await server.method(fsp.writeFile, ["temp.txt", "hello world"]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 09:12:35