我有以下两个问题;
我的循环将运行3次,并产生一次错误(unhandledRejection),而第二次和第三次均无错误。但是结果表明该process.on在每次迭代中均被调用(平均3次)。为什么呢只有在发生unhandledRejection错误时,才应调用process.on,而不是其他情况?我的代码有什么问题?
如果我想在process.on函数中访问'tx'的成员变量(即tx.n,tx.to等)并保存它们...,我该怎么做?
这是我的代码
const abcWeb = require('abc-web');
const abcWeb = new abcWeb('http://testnet-jsonrpc.abc-xyz.org:12537');
const abTx = require('abc-transaction');
var n = 12;
var gp = 10;
var gl = 21000;
var to = '5989d50787787b7e7';
var value = 70;
var limit = 3;
var i=1;
for (i = 0; i < limit; i++) {
try{
const tx = new abTx({
n: n,
gp: gp,
gl:gl ,
to: to,
value:value ,
});
abTx.sign(Buffer.from('8f2016c58e898238dd5b4e00', 'hex'));
abcWeb.abx.sendSignedTransaction('0x' + tx.serialize().toString('hex'));
console.log(abTx);
} catch (exception) {
var message = exception.message;
console.log(message);
}
// n +=1;
}
process.on('unhandledRejection', error => {
console.log("Rejected due to ",error)
})
输出为
由于错误而被拒绝:节点错误:{“代码”: 由于错误而被拒绝:节点错误:{“代码”: 由于错误而被拒绝:节点错误:{“代码”:
答案 0 :(得分:0)
首先在循环内使用try ... catch将为您带来意想不到的结果,以获得更多参考外观here。
现在,对于您的第一个查询,您应该尝试进行黑客攻击以获得预期结果,
只需将try ... catch块放入函数中,然后调用它即可。
for (i = 0; i < limit; i++) {
const tx = new abTx({
n: n,
gp: gp,
gl:gl ,
to: to,
value:value ,
});
myTryCatch(tx, abTx, abcWeb);
}
function myTryCatch(tx, abTx, abcWeb){
try{
abTx.sign(Buffer.from('8f2016c58e898238dd5b4e00', 'hex'));
abcWeb.abx.sendSignedTransaction('0x' + tx.serialize().toString('hex'));
console.log(abTx);
} catch (exception) {
var message = exception.message;
console.log(message);
}
}