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

Node.js报错:await仅在async函数中有效(Hedera SDK场景)

解决"Await is only valid in async functions"错误

问题根源

你虽然尝试了异步自执行函数,但没有把所有包含await的代码逻辑全部放入该函数内部,导致await仍处于非async的全局作用域中,因此报错。

修正后的完整代码

将所有依赖await的操作(包括客户端初始化、账户创建、余额查询等)全部包裹进异步自执行函数,并添加错误捕获逻辑:

const {
 Client, 
 PrivateKey, 
 AccountCreateTransaction, 
 AccountBalanceQuery, 
 Hbar 
} = require("@hashgraph/sdk");
require("dotenv").config();

(async () => {
    // 从.env文件获取测试网账户ID和私钥
    const myAccountId = process.env.MY_ACCOUNT_ID;
    const myPrivateKey = process.env.MY_PRIVATE_KEY;

    // 验证环境变量是否存在
    if (myAccountId == null || myPrivateKey == null ) {
        throw new Error("必须配置myAccountId和myPrivateKey环境变量");
    }

    // 连接Hedera测试网
    const client = Client.forTestnet();
    client.setOperator(myAccountId, myPrivateKey);

    // 生成新账户密钥对
    const newAccountPrivateKey = PrivateKey.generateED25519(); 
    const newAccountPublicKey = newAccountPrivateKey.publicKey;

    // 创建初始余额1000tinybar的新账户
    const newAccount = await new AccountCreateTransaction()
        .setKey(newAccountPublicKey)
        .setInitialBalance(Hbar.fromTinybars(1000))
        .execute(client);

    // 获取新账户ID
    const getReceipt = await newAccount.getReceipt(client);
    const newAccountId = getReceipt.accountId;

    console.log("新账户ID:" + newAccountId);

    // 查询新账户余额
    const accountBalance = await new AccountBalanceQuery()
        .setAccountId(newAccountId)
        .execute(client);

    console.log("新账户余额:" + accountBalance.hbars.toTinybars() + " tinybar.");
})().catch(err => {
    console.error("执行出错:", err);
    process.exit(1);
});

核心要点

  • 所有使用await的语句必须直接位于async函数内部,全局作用域或非async函数中不允许使用await。
  • 新增.catch()处理异步流程中可能抛出的异常,避免出现未捕获的Promise错误。
  • Node.js 12.x完全支持该写法,确保直接通过Node.js运行代码文件即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 20:33:15