javascript - How do I conditionally perform a second task using Promises? -


i'm using bookshelf.js, promise-based orm module, perform couple database lookups. given key user provides, need determine if key matches record in 1 of 2 tables. if find in first table, need return record. however, if don't find in first table, need in second table. basically, need conditionally execute then block. how accomplish using promises? here's have, messy, and, in fact, i'm little unclear happens if call resolve in first school lookup -- second then block execute well?

exports.findtargetrecord = function(code){      return new promise(function(resolve, reject){         schools         .query({ where: { code: code }})         .fetchone()         .then(school => {             if(school) return resolve(school);             return organizations                     .query({ where: { code: code }})                     .fetchone();         })         .then(org => {             if(org) return resolve(org);             resolve(null);         })         .catch(err => reject(err));     }); }; 

is there cleaner way write this?

use promises proxies , regular if:

exports.findtargetrecord = function(code){    const school = schools.query({ where: { code: code }}).fetchone();   school = school.then(school =>      school || organizations.query({ where: { code: code }}).fetchone())   return school; } 

or coroutines bluebird supports (bluebird ships bookshelf):

exports.findtargetrecord = promise.coroutine(function*(code) {    var school = yield schools.query({ where: { code: code }}).fetchone();    if(school) return school;    return organizations.query({ where: { code: code }}).fetchone(); }); 

Comments

Popular posts from this blog

serialization - Convert Any type in scala to Array[Byte] and back -

matplotlib support failed in PyCharm on OSX -

python - Matplotlib: TypeError: 'AxesSubplot' object is not callable -