【问题标题】:Using a props Variable in an async Function在异步函数中使用 props 变量
【发布时间】:2021-08-30 06:19:44
【问题描述】:

我在 vue.js 组件中接收到 web3 的值。我之前在同一组件的代码中成功地使用了这个变量。但是,在尝试在异步函数中使用它时,我在所述变量上收到未定义的错误。我不应该像下面这样使用它,还是我错过了什么? (blockNum 在我的代码前面被分配了一个值。)

 props: ['web3']

 async function getTimestamp () {
     const block = await this.web3.eth.getBlock(blockNum)
     const ts = await this.web3.eth.getBlock(block).timestamp
     return ts
 }
 console.log(getTimestamp())  

【问题讨论】:

  • 使用你的调试器。我怀疑您的this 正在更改,因为getTimestamp() 的调用者绑定不足。
  • console.log(getTimestamp()) [object Promise] 打印到控制台。
  • 能否请您发布您的组件的整个代码?您当前的 sn-p 无法编译。
  • console.log(getTimestamp()) 在没有 this 值的情况下调用 getTimestamp。目前尚不清楚您期望它指的是什么。
  • ts 添加到数据中,然后代替return ts,执行this.ts = ts,然后在创建或挂载的钩子中调用this.getTimestamp(),如果可能未填充web3,则应添加watch:{ web3(v){ if (v) this.getTimestamp() }} 等,然后只需访问 ts 值,您不需要从方法中返回东西,这就是模型的用途

标签: javascript vue.js async-await


【解决方案1】:

由于getTimestamp 是一个异步函数,它返回一个承诺而不是实际值。因此,在控制台记录它之前,您必须等待承诺解决。

async function getTimestamp () {
 const block = await this.web3.eth.getBlock(blockNum)
 const ts = await this.web3.eth.getBlock(block).timestamp
 return ts
}

getTimestamp().then(ts => {
    console.log(ts)
}

【讨论】:

  • 谢谢@Kenneth Lew
猜你喜欢
  • 2020-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-08
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
相关资源
最近更新 更多