Javascript 不要在承诺中看到功能
我有以下代码:Javascript 不要在承诺中看到功能,javascript,Javascript,我有以下代码: var c = function(address, abiJson){ var _ = this; this.data = { wallet: false, account:{ address: false }, contract:{ address: address } }
var c = function(address, abiJson){
var _ = this;
this.data = {
wallet: false,
account:{
address: false
},
contract:{
address: address
}
};
this.abi = $.getJSON(abiJson, function(abi){
_.data.abi = abi;
if(typeof web3 !== 'undefined'){
window.web3 = new Web3(web3.currentProvider);
window.cont = web3.eth.contract(abi).at(address);
}
});
this.getData = function(cb){
if(typeof _.data.abi !== 'undefined'){
_.updateData.done(() => {
cb(_.data);
});
}
else{
_.abi.then(() => {_.updateData
})
.done(() => {
cb(_.data);
});
}
}
this.updateData = Promise.all([
_.get('x'),
_.get('y')
])
.then(values => {
_.data.x.y= values[0];
_.data.x.z= values[1];
})
.then(() => {
Promise.all([
_.get('v', 1),
_.get('v', 2),
])
.then(values => {
_.data.y = values;
});
});
this.get = function(method, args){
return new Promise(function(resolve, reject) {
window.cont[method](args, function(error, result){
if(!error) resolve(result);
});
});
}
}
当我得到函数\uu.get('x')。然后((x)=>console.log(x))
在updateData函数之外,我得到所有数据。但是当我调用getData
函数时,我得到了所有get函数的错误
我只是不知道我的错在哪里。我是js中使用Promise的新手。\p>变量不能这样使用。您可以在将其作为函数调用时使用它,但在创建对象时不能使用它。
可以使用函数的bind绑定作用域。对于箭头功能,将保留范围。请尝试以下代码。对于所有函数,我只是用这个替换了uu,并将其绑定到getJSON的回调中。如果您在那里也使用箭头函数,则不需要绑定
var c = function(address, abiJson){
this.data = {
wallet: false,
account:{
address: false
},
contract:{
address: address
}
};
this.abi = $.getJSON(abiJson, function(abi){
this.data.abi = abi;
if(typeof web3 !== 'undefined'){
window.web3 = new Web3(web3.currentProvider);
window.cont = web3.eth.contract(abi).at(address);
}
}.bind(this));
this.getData = function(cb){
if(typeof this.data.abi !== 'undefined'){
this.updateData.done(() => {
cb(this.data);
});
}
else{
this.abi.then(() => {this.updateData
})
.done(() => {
cb(this.data);
});
}
}
this.get = function(method, args){
return new Promise(function(resolve, reject) {
window.cont[method](args, function(error, result){
if(!error) resolve(result);
});
});
}
this.updateData = Promise.all([
this.get('x'),
this.get('y')
])
.then(values => {
this.data.x.y= values[0];
this.data.x.z= values[1];
})
.then(() => {
Promise.all([
this.get('v', 1),
this.get('v', 2),
])
.then(values => {
this.data.y = values;
});
});
}
以下是问题的简化版本:
var C=function(地址,abiJson){
var=这个;
this.updateData=Promise.all([
_.get('x'),
_.get('y'))
]);
this.get=函数(arg){return Promise.resolve(arg)};
}
var c=新的c();
c、 然后(值=>console.log(值))代码>这一行的问题?:`.abi.then(()=>{.updateData})`您没有显式返回updateData中的值以允许对承诺进行链接。当您打算使用then()时,请确保添加return语句。请重新编写代码。u.get不是函数-我在consoleWhen and how do you callc
中看到此错误。如果不将其作为构造函数或对象方法调用,“\”是全局对象。不确定你所说的“呼叫外部”是什么意思-我们如何重现问题?更新了代码。将get函数放在updateData函数之前。\uu
是一个完全有效的变量名。我相信“lodash”库会为库调用保留它,但这里不是这样。我不是说uu变量无效。我只是说,在实例化对象时,变量不能这样使用。是的,你是对的。一点也不。我不得不重写一点代码,因为我发现了一些错误。但是你给了我正确的方法,谢谢。请看更新后的答案和前后的例子。是的,你是对的。你给我指明了正确的方向。你也是对的,谢谢