Javascript

Ethers.js:使用等待呼叫常量方法不起作用

  • November 10, 2019

如果我嘗試使用以下方法獲取常量函式呼叫的結果:

let gameCountAwait = await contract.getGameEntry(0);

它失敗了:

未擷取的 SyntaxError:await 僅在非同步函式中有效

而如果使用.then它有效:

let gameCount = contract.getGameEntry(0).then(function(res,err){console.log(res[2]);});
  • Ethers.js 版本:4.0.39
  • 提供者:元遮罩
  • 網路:羅普斯滕

以下是重要的完整程式碼:

const ethers = require('ethers');
// The Contract interface
let abi = [
 "event GameResult(bool won)",
 "function lottery(uint8 guess) returns (bool value)",
 "function getGameCount() view returns (uint value)",
 "function getGameEntry(uint index) public view returns(address addr, uint amountBet, uint8 guess, bool winner, uint ethInJackpot)"
];

// Connect to the network
const provider = new ethers.providers.Web3Provider(web3.currentProvider);
let contractAddress = "0x7f8b9483b79f735C34820497A1a7f9FB82C9224b";

let contract = new ethers.Contract(contractAddress, abi, provider);
let gameCount = contract.getGameEntry(0).then(function(res,err){console.log(res[2]);}); //Works!
// let gameCountAwait = await contract.getGameEntry(0); //Does NOT work!
console.log(gameCount);

第一次玩 Ethers.js。希望它是 web3.js 的有效替代品。謝謝你的支持!

來自MDN

await 運算符用於等待 Promise。它只能在非同步函式中使用。

如果您不想使用async功能,可以嘗試:

// ...

let gameCount;
contract.getGameEntry(0).then(function (res, err) {
   gameCount = res[2];
   // ganeCount is only available here
   // to make it available outside, use async/await notation
   console.log(gameCount);
}); 

Ethers.js 與您的問題無關。這只是通用的 Javascript 要求,await只能在非同步函式中使用。有關詳細資訊,請參閱文件

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