api循环调用后Node.JS发送响应 [英] Node.JS send response after api call in loop

查看:73
本文介绍了api循环调用后Node.JS发送响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检索对象列表,并将其发送回我的移动应用程序.实际上,在forstrong循环结束后 之后,实际上很难发送它们.

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.

我尝试将变量"data"附加到数组,然后将其发送到循环外,但该数组为空.显然,有正在检索的数据,但没有按时推送到数组中.

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.

如何在调用res.send()之前确保循环结束?我尽可能地减少了代码,以使其尽可能简单.

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

推荐答案

跟踪来自API的响应.收到所有答复后,呼叫res.send.

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

这篇关于api循环调用后Node.JS发送响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆