Javascript

SyntaxError: await 僅在非同步函式中有效

  • June 23, 2021

我不明白為什麼我有語法錯誤?我正在嘗試執行我的測試 javascript,可在此處獲得

const assert = require('assert');
const ganache = require('ganache-cli');
const Web3 = require('web3');
const web3 = new Web3(ganache.provider());

let accounts;

beforeEach(() => {
   // Get list of all accounts
   accounts = await web3.eth.getAccounts();
   // Use one of those accounts to deploy the contract
});

describe('Inbox', ()=>{
   it('deploys a contract', ()=> {
       console.log(accounts);
   });
} );

在 PowerShell 上執行“npm run test”時出現此錯誤

> inbox@1.0.0 test C:\inbox
> mocha


C:\inbox\test\Inbox.test.js:10
       accounts = await web3.eth.getAccounts();
                  ^^^^^

SyntaxError: await is only valid in async function
   at wrapSafe (internal/modules/cjs/loader.js:1001:16)
   at Module._compile (internal/modules/cjs/loader.js:1049:27)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
   at Module.load (internal/modules/cjs/loader.js:950:32)
   at Function.Module._load (internal/modules/cjs/loader.js:790:14)
   at ModuleWrap.<anonymous> (internal/modules/esm/translators.js:199:29)
   at ModuleJob.run (internal/modules/esm/module_job.js:169:25)
   at async Loader.import (internal/modules/esm/loader.js:177:24)
   at async formattedImport (C:\inbox\node_modules\mocha\lib\esm-utils.js:7:14)
   at async Object.exports.requireOrImport (C:\inbox\node_modules\mocha\lib\esm-utils.js:48:32)
   at async Object.exports.loadFilesAsync (C:\inbox\node_modules\mocha\lib\esm-utils.js:73:20)
   at async singleRun (C:\inbox\node_modules\mocha\lib\cli\run-helpers.js:125:3)
   at async Object.exports.handler (C:\inbox\node_modules\mocha\lib\cli\run.js:366:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! inbox@1.0.0 test: `mocha`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the inbox@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\AppData\Roaming\npm-cache\_logs\2021-06-23T14_04_34_840Z-debug.log
PS C:\inbox>

有人可以幫助我了解如何解決此問題嗎?

您需要將 beforeEach 內部的回退方法更改為非同步方法,如下所示:

beforeEach(async() => {
   // Get list of all accounts
   accounts = await web3.eth.getAccounts();
   // Use one of those accounts to deploy the contract
});

引用自:https://ethereum.stackexchange.com/questions/102352