This is my async function:
const returnNumberOfFoods = async() => {
const web3 = new Web3(url);
// const networkId = await web3.eth.net.getId();
const myContract = new web3.eth.Contract(
Contract.abi,
Contract.address
);
let result;
await myContract.methods.numberOfFoods().call(function(err, res) {
result = res;
});
return result;
}
And this is how I am trying to get value:
const numberOfCardsPromise = returnNumberOfFoods();
const numberOfCards = numberOfCardsPromise.then(value => { return value; });
console.log(numberOfCards);
But this is what I get in console:
Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: "4"
The PromiseResult is my desired output.
Have 2 ways:
First:
const numberOfCards = await returnNumberOfFoods();
Second:
returnNumberOfFoods().then((return) => {
console.log(return);
});
There are many ways to solve your problem. However, mixing synchronous and asynchronous code is not one of them.
A potential solution would be to work with the then statement:
async function test(){
return true
}
test().then(value => {
console.log(JSON.stringify(value) + " (I'm asynchronous!)") //works
})
console.log(test()) //doesn't work, returns unfulfilled promise
You can also declare another await statement - but note that this has to be inside another async function, as synchronous code will not 'pause' until the value is defined.
async function test(){
return true
}
async function logValueAsync(){
value = await test()
console.log(JSON.stringify(value) + " (I'm asynchronous!)") //works
}
function logValueSync(){
value = test() //await actually generates an error as it is in a synchronous function
console.log(value) //doesn't work, returns unfulfilled promise
}
logValueAsync()
logValueSync()
Note that while it may show that the sync code returns {}, in reality it is a promise. You can run this in your browser console to see what I'm talking about.
This will give you the value:
const numberOfCards = await returnNumberOfFoods();
console.log(numberOfCards) // desired result