Search code examples
javascriptasync-awaitweb3js

Async/await order issue in web3.js callback




The problem is showing I'm using 2 async function one by one. Each of them calls the method from the smart contract and doing other staff on 'receipt' callback.

The code is:

await first()
await second()

let first = async function () {
   await myContract.methods.methodOne()
   .send({from: account})
   .on('receipt', async () => {
    console.log('1')
    async someAsyncFunction()
   })
}

let second = async function () {
   await myContract.methods.methodOne()
   .send({from: account})
   .on('receipt', async () => {
    console.log('2')
    console.log(variableFromContract) // undefined
   })
}

let someAsyncFunction = async function () {
   setTimeout(() => {
      variableFromContract = 10;
   }, 2000);
}

What's the problem with someAsyncFunction?
Why it's not running before the second() function?

Thanks in advance. (I'm using web3.js 1.0.0-beta.37 version)


Solution

  • I found the answer after many tries, no needed put an async method inside 'receipt' callback, just use

    ...
    .on('receipt', () => {
        console.log('block mined') 
    })
    .then( async () => { 
        await someAsyncFunction() // put the code here
    })