Last active
April 30, 2018 10:49
-
-
Save akari0624/e015d983a364d664da3ea8d5ba44a396 to your computer and use it in GitHub Desktop.
Node.js api end point, when do mongoDB query, promise or async/await example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
a node.js api end point , query 2 times via mongoose, first query by orderId that get OrderInfo, which incllude a vendorId, | |
then use vendorId to query VendorInfo, finally send OrderInfo and VendorInfo to client | |
*/ | |
const Order = require('./Order'); | |
const VendorModel = require('../Vendor'); | |
// by not nested promise chain, but has side-effect | |
exports.get_joinOrder_initInfo1 = (req, res, next) => { | |
const orderId = req.body.orderId; | |
console.log('orderId :', orderId); | |
let orderDataKeeper; // <= side-effect | |
Order.findOne({ _id: orderId }) | |
.then(orderData => { | |
orderDataKeeper = orderData; // <= | |
return VendorModel.findOne({ _id: orderData.vendor_id }); | |
}) | |
.then(vendorData => { | |
res.json({ | |
errorMsg: '', | |
joinOrderInfo: { | |
orderInfo: orderDataKeeper, | |
vendorInfo: vendorData | |
} | |
}); | |
}) | |
.catch(e => { | |
res.json(res.json({ errorMsg: 'ERROR ERROR!!', joinOrderInfo: {} })); | |
}); | |
}; | |
// // by nested promise,no side-effect, though looks really dirty, but you can do very sophisticated error-handling | |
exports.get_joinOrder_initInfo2 = (req, res, next) => { | |
const orderId = req.body.orderId; | |
console.log('orderId :', orderId); | |
Order.findOne({ _id: orderId }) | |
.then(orderData => { | |
VendorModel.findOne({ _id: orderData.vendor_id }) | |
.then( | |
vendorData => { | |
res.json({ | |
errorMsg: '', | |
joinOrderInfo: { | |
orderInfo: orderData, | |
vendorInfo: vendorData | |
} | |
}); | |
} | |
).catch(e => { | |
res.json(res.json({ errorMsg: 'ERROR when query VENDOR info!!', joinOrderInfo: {} })); | |
}); | |
}) | |
.catch(e => { | |
res.json(res.json({ errorMsg: 'ERROR when query ORDER info!!', joinOrderInfo: {} })); | |
}); | |
}; | |
// by async await, looks nice, but you need to try catch all the block to do the error-handling | |
exports.get_joinOrder_initInfo3 = async (req, res, next) => { | |
try { | |
const orderId = await req.body.orderId; | |
console.log('orderId :', orderId); | |
const orderData = await Order.findOne({ _id: orderId }); | |
const vendorData = await VendorModel.findOne({ | |
_id: orderData.vendor_id | |
}); | |
res.json({ | |
errorMsg: '', | |
joinOrderInfo: { | |
orderInfo: orderData, | |
vendorInfo: vendorData | |
} | |
}); | |
} catch (e) { | |
res.json(res.json({ errorMsg: 'ERROR ERROR!!', joinOrderInfo: {} })); | |
} | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment