【发布时间】:2018-02-17 23:25:56
【问题描述】:
我正在尝试检索对象列表并将它们发送回我的移动应用程序。我只是在在 forEach 循环结束后实际发送它们时遇到了一些困难。
我尝试将该变量“数据”附加到一个数组并将其发送到循环之外,但该数组是空的。显然,有数据被检索,但它没有按时推送到数组中。
在调用 res.send() 之前,如何确保循环结束?我尽可能地减少代码以使其尽可能简单。
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
});
});
});
};
【问题讨论】:
标签: javascript node.js loops express asynchronous