Petras Petras - 4 days ago 5
Javascript Question

How to make multiple 'if' statements currectly (node.js)

I have this try statement and I wanted to update it with more if's and make it to try 2 more times before finally declining the offer. I did not succeed. I have no idea how to do them correctly. Does anyone know how to fix my statement after?

STATEMENT BEFORE (WORKS)

try {
offers.acceptOffer({tradeOfferId: offer.tradeofferid}, function(err, log) {
if (err) {
helper.log('Error accepting trade offer ' + offer.tradeofferid, 891, err);
offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
});
return;
}


STATEMENT AFTER (DON'T WORK)

try {
offers.acceptOffer({tradeOfferId: offer.tradeofferid}, function(err, log) {
if (err) {
helper.log('Error accepting trade offer: 1st try' + offer.tradeofferid, 891, err);
offers.acceptOffer({tradeOfferId: offer.tradeofferid}, function(err, log) {
if (err) {
helper.log('Error accepting trade offer: 2nd try ' + offer.tradeofferid, 891, err);
offers.acceptOffer({tradeOfferId: offer.tradeofferid}, function(err, log) {
if (err) {
helper.log('Error accepting trade offer: 3rd try ' + offer.tradeofferid, 891, err);
offers.acceptOffer({tradeOfferId: offer.tradeofferid}, function(err, log) {
if (err) {
helper.log('Offer declined: failed 3 times ' + offer.tradeofferid, 891, err);
offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
});
return;
}

Answer

That code looks hard to read and maintain. It might work, but like you said, adding another few checks is a nightmare.

Take a look at the async library, namely the retry function

Now you code would look something like this: (code untested)

async.retry(3, function( retryCb, prevResult){ offers.acceptOffer({tradeOfferId: offer.tradeofferid}, retryCb); }, function(err, result) { if( err){ //decline offer } // do something with the result });

Now it's easy to add more checks, change the delay, etc. Thanks for helping with control flow, async! : )

Comments