This is the code written using q library .
update = (selectionCriteria, updateCriteria, updateOptions, options) => {
let q = Q.defer()
, db = options.db
, logger = options.logger
db.collection(collectionName).update(selectionCriteria, updateCriteria, updateOptions, (err, doc) => {
if (err) {
logger.error(err)
q.reject(new Error("SOMETHING_WENT_WRONG",options))
}
if(doc.result.n > 0)
q.resolve(true)
else
q.resolve(false)
logger.info("Updating")
})
return q.promise
}
What i'm not able to understand is how logger.info is able to execute even after the q.resolve(false) has been done ?
Doesn't q.resolve(false) short-circuit the flow ?
Neither resolve not reject break the program's flow. Defers work like a normal Promises. They just fire an async event with the result of the Promise. The evaluation and calling of the resolve-/reject-handler will happen later, and the execution is queued by the JS VM.
If you need to break the flow at that point, you might want to use a
return;statement:const update = (selectionCriteria, updateCriteria, updateOptions, options) => { let q = Q.defer() , db = options.db , logger = options.logger db.collection(collectionName).update(selectionCriteria, updateCriteria, updateOptions, (err, doc) => { if (err) { logger.error(err) q.reject(new Error("SOMETHING_WENT_WRONG",options)) } if(doc.result.n > 0) q.resolve(true) else { q.resolve(false) return } logger.info("Updating") }) return q.promise }