I am a javascript newbie, i have a problem with the following code. Am trying to set a price value from callback, but isn't working... Any help please?
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
}
});
});
if i'm not mistaken, the closure gets the last value of j. so if the iteration runs from 0 to 3 then you always have self.work[3].workprice = 300; (try tracing).
try working with a library li lodash and turn you code into something like this:
_.each(this.work, function(item) {
Price.findOne(
{ "item": item.workproduct },
function(err, val) {
// item.workprice ...
}
);
});
also, if this is the real code then it's missing a '}' before the last ')'.
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);
});
Reviewing the doc, i also tried, passing the context variable on the _.each
_.each(this.work, function(item) {
Price.findOne({
"item": item.workproduct
}, function(err, val) {
item.workprice = 100;
});
}, this); <-- passing 'context'
But isn't assigning the value yet...