web3.js回调中的异步/等待订单问题

时间:2018-12-21 15:08:46

标签: javascript async-await web3js



问题显示我正在一个接一个地使用2个异步函数。他们每个人都从智能合约中调用该方法,并在“回执”回调中执行其他工作。

代码是:

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

someAsyncFunction有什么问题?
为什么它在second()函数之前没有运行?

先谢谢了。 (我使用的是web3.js 1.0.0-beta.37版本)

2 个答案:

答案 0 :(得分:0)

经过多次尝试,我找到了答案,不需要在'receipt'回调中放入异步方法,只需使用

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

答案 1 :(得分:0)

这里有几个问题:

let first = async function () {
   await myContract.methods.methodOne()
   .send({from: account})
   .on('receipt', async () => {
    console.log('1')
    async someAsyncFunction() // <--- should be return await someAsyncFunction() so you have a value to pass onto second
   })
}

let second = async function () {
   await myContract.methods.methodOne()
   .send({from: account})
   .on('receipt', async () => { // <-- this is an async function but you don't await anything inside of it
    console.log('2')
    console.log(variableFromContract) // undefined
   })
}

let someAsyncFunction = async function () { // again async function but awaiting nothing to resolve.
   setTimeout(() => {
      variableFromContract = 10;
   }, 2000);
}