Handling nested callbacks/promises with Mongoose -
i beginner node.js , mongoose. spent entire day trying resolve issue scouring through so, not find right solution. basically, using retrieved values 1 collection query another. in order this, iterating through loop of retrieved results.
with iteration, able populate results need. unfortunately, area having issue response being sent before required information gathered in array. understand can handled callbacks/promises. tried numerous ways, haven't been successful attempts. trying make use of q library facilitate callbacks. i'd appreciate insight. here's snippet of portion i'm stuck:
var length = object.keys(purchasesarray).length; var jsonarray = []; var getproductdetails = function () { var deferred = q.defer(); (var = 0; < length; i++) { var property = object.keys(purchasesarray)[i]; if (purchasesarray.hasownproperty(property)) { var productid = property; var productquery = product.find({asin: productquery.exec(function (err, productlist) { jsonarray.push({"productname": productlist[0].productname, "quantity": purchasesarray[productid]}); }); } } return deferred.promise; }; getproductdetails().then(function sendresponse() { console.log(jsonarray); response = { "message": "the action successful", "products": jsonarray }; res.send(response); return; }).fail(function (err) { console.log(err); }) });
i particularly able send 1 of 2 objects in jsonarray
array response being sent after first element.
update
thanks roamer-1888 's answer, have been able construct valid json response without having worry error of setting headers after sending response.
basically, in getproductdetails()
function, trying retrieve product names mongoose query while mapping quantity each of items in purchasesarray
. function, eventually, form following response:
response = { "message": "the action successful", "products": jsonarray };
where, jsonarray
in following form getproductdetails
:
jsonarray.push({ "productname": products[index].productname, "quantity": purchasesarray[productid] });
on assumption purchasesarray
result of earlier query, appear trying :
- query database once per
purchasesarray
item, - form array of objects, each containing data derived query , original
purchasesarray
item.
if so, , few other guesses, following pattern should job :
var getproductdetails = function() { // map purchasesarray array of promises var promises = purchasesarray.map(function(item) { return product.findone({ asin: item.productid // property of desired item }).exec() .then(function product { // here can freely compose object comprising data : // * synchronously derived `item` (an element of 'purchasesarray`) // * asynchronously derived `product` (from database). // `item` still available "closure". // example : return { 'productname': product.name, 'quantity': item.quantity, 'unitprice': product.unitprice }; }) // here, catching, no individual error cause whole response fail. .then(null, (err) => null); }); return promise.all(promises); // return promise settles when `promises` fulfilled or 1 of them fails. }; getproductdetails().then(results => { console.log(results); // `results` array of objects composed in getproductdetails(), properties 'productname', 'quantity' etc. res.json({ 'message': "the action successful", 'products': results }); }).catch(err => { console.log(err); res.sendstatus(500); // or similar });
your final code differ in detail, particularly in composition of composed object. don't rely on guesses.
Comments
Post a Comment