如果我试图通过以下方法获得常数函数调用的结果:
let gameCountAwait = await contract.getGameEntry(0);它失败了,因为:
未定义的SyntaxError:等待仅在异步函数中有效
然而,如果使用.then,则可以:
let gameCount = contract.getGameEntry(0).then(function(res,err){console.log(res[2]);});以下是整个代码,以备不时之需:
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的有效替代。多谢你们的支持!
发布于 2019-11-09 14:36:16
来自MDN:
等待操作员用来等待承诺。它只能在异步函数中使用。
如果不想使用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);
}); 发布于 2019-11-09 14:20:07
Ethers.js与您的问题无关。这只是一般的Javascript要求,await只能在异步函数中使用。详情请参见文档。
https://ethereum.stackexchange.com/questions/77348
复制相似问题