Amin Shah Gilani
Amin Shah Gilani

Reputation: 9826

Making async callback functions in nodejs

I have confusing code that I'd like to modularize. I have a general ledger implemented in Mongodb. Transferring credits from john to adam appends the following document in the db.dummyTx:

{
  "debitAccount": "john",
  "creditAccount": "adam",
  "amount": 10
}

I'd like to create a single function transfer(from, to, amount, callback()) where callback receives the transaction document/object.

I've created the following using the async module:

function transfer(from, to, amount, acallback) {
  async.waterfall([
      function(callback) {
        userBalance(from);
        userBalance(to);
        callback(null);
      },
      function(callback) {
        var transaction = new dummyTx();
        transaction.creditAccount = from; // in the account of the sender
        transaction.debitAccount = to; // with reference to the reciever
        transaction.amount = amount; // of the given amount
        transaction.save(function(err) {
          callback(null, transaction);
        });
      },
      function(transaction, callback) {
        console.log("Credited User " + transaction.creditAccount +
          " and debited User " + transaction.debitAccount + " by amount " +
          transaction.amount + "credits");
        callback(null, transaction);
      },
      function(transaction, callback) {
        userBalance(transaction.creditAccount);
        userBalance(transaction.debitAccount);
        callback(null, transaction);
      }
    ],
    acallback(err, transaction)
  );
}

My rationale was that if I pass function(err,transaction){if err console.log(err);} as acallback, it would run as the final callback in the end. However, it says err is undefined in acallback(err, transaction)

Bear with me, I just discovered async yesterday, so I'm a figurative five year old.

My second thought was to save the chain of functions into an Array named transfer and to call it as async(transfer,function(err,transaction){if err console.log(err)}; if I can't get this to work.

Edit: I'd also like the acallback parameter to be optional.

Upvotes: 2

Views: 247

Answers (1)

Trott
Trott

Reputation: 70055

If you have defined the function acallback, then you should just pass that, and not the parameters. In other words, instead of this:

...
      }
    ],
    acallback(err, transaction)
  );
}

...use this:

...
      }
    ],
    acallback
  );
}

To make acallback() optional, you can do a number of things. A couple things that leap to mind:

  • Before calling, async.waterfall(), check to see if acallback() is defined. If it is not, set it to a no-op function.

  • Before calling async.waterfall(), check to see if acallback() is defined. If it is not, invoke async.waterfall() without it. If it is, invoke it with it.

Upvotes: 1

Related Questions