I have following two questions;
My loop will run for three-time, and produced error (unhandledRejection) for one time and no errors for the 2nd and 3rd. But the results show that process.on called on every iteration (means three times). Why ? process.on should be called only for when unhandledRejection error occurs, not for others ??? What is wrong with my code?
If i want to access my member variables of 'tx' (i.e. tx.n, tx.to, etc.) in process.on function and want to save them..., how could I do that?
Here is my code
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)
})
Output is
Rejected due to Error: Node error: {"code": Rejected due to Error: Node error: {"code": Rejected due to Error: Node error: {"code":
First of all using try...catch inside a loop will give you unexpected result for more reference look here.
Now for your 1st query you should try following hack to get expected results,
Just Put your try...catch block in a function and call it instead.
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);
}
}