Node.js错误显示await仅在JavaScript函数中有效

z4bn682m  于 12个月前  发布在  Node.js
关注(0)|答案(1)|浏览(104)

我运行的是Node 12.20.2版本,我使用的是Hedera SDK(https://docs.hedera.com/hedera/getting-started/create-an-account)。当我运行下面的代码时,它会抛出这个错误:
Await仅在JavaScript函数中有效。
我已经试过按照下面的示例代码将代码 Package 在Cockc函数中,但无法使其工作:

(async () => {
 //coding goes here
})();

下面是代码

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

//Grab your Hedera testnet account ID and private key from your .env file
const myAccountId = process.env.MY_ACCOUNT_ID;
const myPrivateKey = process.env.MY_PRIVATE_KEY;

// If we weren't able to grab it, we should throw a new error
if (myAccountId == null || myPrivateKey == null ) {
    throw new Error("Environment variables myAccountId and myPrivateKey must be present");
}

// Create our connection to the Hedera network
// The Hedera JS SDK makes this really easy!
const client = Client.forTestnet();

client.setOperator(myAccountId, myPrivateKey);

//Create new keys
const newAccountPrivateKey = PrivateKey.generateED25519(); 
const newAccountPublicKey = newAccountPrivateKey.publicKey;

//Create a new account with 1,000 tinybar starting balance
const newAccount = await new AccountCreateTransaction()
    .setKey(newAccountPublicKey)
    .setInitialBalance(Hbar.fromTinybars(1000))
    .execute(client);

// Get the new account ID
const getReceipt = await newAccount.getReceipt(client);
const newAccountId = getReceipt.accountId;

console.log("The new account ID is: " + newAccountId);

//Verify the account balance
const accountBalance = await new AccountBalanceQuery()
    .setAccountId(newAccountId)
    .execute(client);

console.log("The new account balance is: " + accountBalance.hbars.toTinybars() + " tinybar.");
y1aodyip

y1aodyip1#

你不能在async函数之外使用await表达式,所以试着像这样使用

(async () => {
code....
})();

相关问题