Lucas
Lucas

Reputation: 3

Node.JS send response after api call in loop

I'm trying to retrieve a list of objects and send them back to my mobile app. I'm just having some difficulty actually sending them after the forEach loop is over.

I tried appending that variable "data" to an array and sending it outside of the loop but the array is empty. Obviously, there is data being retrieved, but it doesn't get pushed into the array on time.

How can I make sure the loop is over before I call res.send() ? I reduced the code as much as I could to make it as simple as possible.

var stripe = require("stripe")("stripe_key");

exports.fetchTransactions = function(req, res) {

var account = req.body.account;

stripe.transfers.list({ destination: account}, function(err, transactions) {
 transactions.data.forEach(function(item) {
  stripe.transfers.retrieve(item.id, function(err, transfer) {
    if (err) {
      console.log(err);
    };
    var data = {
      amount: item.amount,
      created: item.created
    };
    // Can't call res.send(data) inside the loop because res.send() can only be called once.
    // But if I call res.send(array) outside of the loop, the array is still empty
   });
  });
 });
};

Upvotes: 0

Views: 1610

Answers (1)

user2652134
user2652134

Reputation:

Keep track of the responses from API. Call res.send when all responses have been received.

var stripe = require("stripe")("stripe_key");

exports.fetchTransactions = function(req, res) {

    var account = req.body.account;

    stripe.transfers.list({
        destination: account
    }, function(err, transactions) {
        var pending= transactions.data.length;
        transactions.data.forEach(function(item) {
            stripe.transfers.retrieve(item.id, function(err, transfer) {
                pending--;
                if (err) {
                    return console.log(err);
                };
                var data = {
                    amount: item.amount,
                    created: item.created
                };
                if (pending == 0) {
                    res.send(array);
                }
            });
        });
    });
};

Upvotes: 1

Related Questions