Node.JS send response after api call in loop

*爱你&永不变心* 提交于 2020-01-06 05:23:23

问题


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:


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


来源:https://stackoverflow.com/questions/46126578/node-js-send-response-after-api-call-in-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!