【发布时间】:2014-11-16 21:32:04
【问题描述】:
我有一个循环,它获取一组用户,然后尝试获取每个用户的信息。使用下面的代码,如果我有两个用户,它会返回相同的信息(最后一个用户)两次。因此,当我尝试更新和保存用户信息时,它只保存最后一个用户的信息。
for (i = 0; i < users.length; i++) {
var amount = users[i].monthlyAmount;
// var stripeID = users[i].stripeID;
// if the amount charged is greater than 0, charge the customer the correct amount
if(amount != '0') {
var stripeID = users[i].stripeID;
accountID = users[i];
// stripe function to charge customer
stripe.charges.create({
amount: amount,
currency: "usd",
customer: stripeID,
description: "Monthly charge"
}, function(err, charge) {
if (err) return (err);
// if there are no errors with charging the customer, proceed to reset the monthly amount
if(!err) {
console.log(accountID);
accountID.monthlyAmount = '0';
accountID.save();
}
});
}
}
这是它的输出:
{ billingInfo: 'true',
createdAt: Sun Nov 16 2014 14:05:21 GMT-0600 (CST),
email: 'a@a.com',
encryptedPassword: '*removed',
monthlyAmount: 1000,
propertyCount: 0,
stripeID: '*removed',
updatedAt: Sun Nov 16 2014 15:10:59 GMT-0600 (CST),
id: '54690381c03a265b07c99564' }
{ billingInfo: 'true',
createdAt: Sun Nov 16 2014 14:05:21 GMT-0600 (CST),
email: 'a@a.com',
encryptedPassword: '*removed',
monthlyAmount: '0',
propertyCount: 0,
stripeID: '*removed',
updatedAt: Sun Nov 16 2014 15:10:59 GMT-0600 (CST),
id: '54690381c03a265b07c99564' }
【问题讨论】:
-
我也尝试使用 accountID 作为非全局变量,但每个用户都变得未定义。
-
您定义的函数是指AccountID,它不是函数本身的本地。所以它会加载函数运行时的任何值。因为这可能是在您的 for 循环完成之后,所以它始终是循环完成时 accountID 的值 - 即最后一个用户的值。
-
如果您将 AccountID 设置为包含 for 循环的函数的本地,那么当计费函数运行时,其他函数已完成,因此 AccountID 未定义
标签: javascript arrays json variables sails.js