1

我是 javascript 新手,我对以下代码有疑问。我正在尝试从回调中设置价格值,但不起作用......请帮忙?

PreInvoiceSchema.pre('save', function(next) {

//Seperating code from state
var codestate = addr[2].split(/[ ,]+/);
this.customer.zipcode = codestate[2];
this.customer.state = codestate[1];

//Calculating base price
if (this.order_subtype == "Upgrade") {
    this.price = 30;
} else {
    this.price = 50;
}
var self = this;

for (var j = 0; j < this.work.length; j++) {

    Price.findOne({
        "item": self.work[j].workproduct
    }, function(err, val) {
        if (self.work[j] != undefined) {
             self.work[j].workprice = 300; <-- this doesn't work
        }
    });
});
4

2 回答 2

0

如果我没记错的话,闭包会得到 j 的最后一个值。所以如果迭代从 0 运行到 3,那么你总是有 self.work[3].workprice = 300; (尝试追踪)。

尝试使用库 li lodash并将你的代码变成这样的东西:

_.each(this.work, function(item) {
    Price.findOne(
        { "item": item.workproduct }, 
        function(err, val) {
            // item.workprice ...
        }
    );
});

此外,如果这是真正的代码,那么它在最后一个 ')' 之前缺少一个 '}'。

于 2013-06-16T21:07:41.903 回答
0
for (var j = 0; j < this.work.length; j++) {
    (function(i) {
        Price.findOne({
            "item": self.work[i].workproduct
        }, function(err, val) {
            if (self.work[i] != undefined) {
                 self.work[i].workprice = 300; <-- this doesn't work
            }
        });
    })(j);
});
于 2013-06-16T21:20:30.017 回答