Reputation: 81
I have an asynchronous function in which I use await for an object to return.
async function createProductsArray(products, numberOfDays) {
if (!products) return [];
var productsArray = [];
for (var i = products.length - 1; i >= 0; i--) {
var product = await productController.read_product(products[i]);
if (product) {
product.total_price = productController.calculate_product_price(product, numberOfDays);
productsArray.push(product);
}
}
console.log(productsArray);
return productsArray;
}
Function calculate_product_price:
exports.calculate_product_price = function (product, days) {
if (days && product.selling_type == 'rental') {
return product.price * days;
}
else {
return product.price;
}
}
For some reason, I can't assign a property total_price to product. It doesn't appear on the returned object of this function. I've tried replacing the property value with static value like 'test' and I've checked if the object is mutable (it is).
Any ideas why this doesn't work? I suspect it has something to do with all this stuff happening inside an async function, but I can't really figure out why.
Function execution is supposed to be halted until await productController.read_product() returns a value, so this should work correctly?
Upvotes: 0
Views: 638
Reputation: 81
It turns out that I was trying to modify an object that came from a Mongoose query.
However, Mongoose doesn't return plain Javascript objects, so modifying them isn't possible. I solved it by adding lean() to the Mongoose query.
More info in this question: Why can't you modify the data returned by a Mongoose Query (ex: findById)
Upvotes: 0
Reputation: 6698
You have 2 async
functions. You'll need to await on both of them. I'm assuming you are doing something like this:
console.log(myProducts, 7);
...somewhere in your code, and the log shows it to be empty. But you also need to wrap that in an await
, because createProductsArray
is also asynchronous:
await console.log(myProducts, 7);
Upvotes: 2