[英]Variable stage keeps coming back undefined
嗨,我正在尝试从函数test()
获取结果,并使用它来设置变量stageIs
但是它总是返回undefined
。 任何帮助将不胜感激,我已经尝试解决了几个小时。
var stage;
import { CONTRACT } from '../contract'
import _ from 'lodash'
export default {
data () {
return {
stageIs: null,
amount: null
}
},
mounted () {
this.coinbase = CONTRACT._eth.coinbase
this.test()
},
methods: {
test () {
CONTRACT.name1(function(err, res) {
stage = (res);
});
alert(stage);
this.stageIs= (stage)
}
当我在test()
执行警报时,它可以工作,但是由于某种原因,它不会设置{{ stageIs }}
。
test () {
CONTRACT.name1(function(err, res) {
stage = (res);
alert(stage)
this.stageIs = (stage)
})
您有一个匿名函数作为CONTRACT.name1
的参数。 通过此匿名函数的签名, name1
似乎是异步的。
结果,对name1
的调用将立即返回,而应该由name1
完成的工作将在事件循环中稍后执行(或正在等待IO)。 结果, stage
将始终是不确定的。
您要做的是:
test () {
let that = this;
CONTRACT.name1(function(err, res) {
stage = (res);
alert(stage)
that.stageIs = stage;
});
}
这里发生两件事。 当异步函数name1
调用回调时,我们将为stage
分配一个值。 我们还this
内部test
分配了一个引用,因为匿名函数将在不同的上下文中执行(因此,匿名函数的this
会指向其他内容)。
或者,您也可以使用箭头函数摆脱this
绑定问题。
test () {
CONTRACT.name1((err, res) => {
stage = (res);
alert(stage)
this.stageIs = stage;
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.