我是Nodejs的新手,我一直在为我的合同编写一个Web3处理程序,一切正常但全局变量在promise执行期间不会更新,即使我在console.log之后也没有任何价值然后。
...
var cityDb = {};
function gettingBalance() {
return new Promise ( (resolve, reject) => {
Contract.totalSupply.call(function(error, result){
if(!error)
{
resolve(result.toNumber());
}
else
reject(error);
});
});
}
function gettingCities(cityNumber) {
return new Promise ( (resolve,reject) => {
Contract.CityDB.call( cityNumber, (error, result) => {
if(!error)
{
resolve(result);
}
else
reject(error);
});
});
}
gettingBalance()
.then ( (result) => {
console.log('Total after function: '+result);
return result;
})
.then ( (totalSupply) => {
console.log('loop data :'+totalSupply);
// START SECOND PROMISE
for (let i=0; i <= totalSupply; i++) {
gettingCities(i)
.then( (result) => {
cityDb[i] = {
cityName: result[0],
Population: result[1],
};
let j = i-1;
console.log('Loop ['+i+']'+ cityDb[i].cityName);
})
.catch( (error) => {
console.log(error);
});
if (i == totalSupply) { return; }
}
// END SECOND PROMISE
})
.then ( (response) => {
console.log('Test promise loop: '+ cityDb[2]);
})
.catch( (err) => {
console.log('loop error: '+err);
});
记录结果:
Total supply after function: 3
loop data :3
Test promise loop: undefined
Loop [0]0x4e657720596f726b000000000000000000000000000000000000000000000000
Loop [1]0x5061726973000000000000000000000000000000000000000000000000000000
Loop [2]0x4e61646f72000000000000000000000000000000000000000000000000000000
Loop [3]0x0000000000000000000000000000000000000000000000000000000000000000
为什么测试保证循环未定义? cityDB没有从循环中获得更新,但循环完全按预期工作。
答案 0 :(得分:0)
问题是你没有正确地链接承诺。您的所有then
来电完成后,您的上次gettingCities
并未等待。为此,您可以使用Promise.all
gettingBalance()
.then((result) => {
console.log('Total after function: ' + result);
return result;
})
.then((totalSupply) => {
console.log('loop data :' + totalSupply);
// START SECOND PROMISE
const promises = [];
for (let i = 0; i < totalSupply; i++) {
// We push gettingCities promises into the array
promises.push(gettingCities(i));
}
// We pass gettingCities promises into Promise.all
return Promise.all(promises);
})
.then((results) => {
// All gettingCities results
// We loop through each result and fill cityDb
results.forEach((result, i) => {
cityDb[i] = {
cityName: result[0],
Population: result[1],
};
console.log('Loop [' + i + ']' + cityDb[i].cityName);
})
console.log('Test promise loop: ' + cityDb[2]);
})
.catch((err) => {
console.log('loop error: ' + err);
});
您可以删除全局cityDb
,并在上一个.then
.then((results) => {
// gettingCities results
const cityDb = {};
results.forEach((result, i) => {
cityDb[i] = {
cityName: result[0],
Population: result[1],
};
console.log('Loop [' + i + ']' + cityDb[i].cityName);
})
console.log('Test promise loop: ' + cityDb[2]);
})