0

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
   });
  });
 });
};

1 Answer 1

1

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);
                }
            });
        });
    });
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.