0

If I try to get the result of a constant function call with:

let gameCountAwait = await contract.getGameEntry(0);

it fails with:

Uncaught SyntaxError: await is only valid in async function

Whereas if using .then it works:

let gameCount = contract.getGameEntry(0).then(function(res,err){console.log(res[2]);});
  • Ethers.js Version: 4.0.39
  • Provider: Metamask
  • Network: Ropsten

Here is the whole code in case that matters:

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);

First time ever playing around with Ethers.js. Hope it is a valid alternative to web3.js. Thanks for your support!

closed as off-topic by Ismael, Majd TL, Niklas Feurstein, Achala Dissanayake, shane Nov 11 at 16:37

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question does not appear to be about Ethereum, the decentralized application platform and smart contract enabled blockchain, within the scope defined in the help center." – Ismael, Majd TL, Niklas Feurstein, Achala Dissanayake, shane
If this question can be reworded to fit the rules in the help center, please edit the question.

  • that is js error, you can use await only in async functions. nothing to do with web3 and ethers – Majd TL Nov 10 at 9:30
0

From MDN:

The await operator is used to wait for a Promise. It can only be used inside an async function.

if you don't want to use async function, you can try:

// ...

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);
}); 
0

Ethers.js is not related to your problem. This is just generic Javascript requirement, that await may only be used inside asynchronous function. See documentation for details.

  • Thanks! I shouldn't have just copied the example code and use my brain instead... – René K Nov 9 at 14:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.