Per Ström Per Ström - 21 days ago 9
Javascript Question

Chaining a promise

I check if a post exists in table. If it does not, I insert it. So I need to make two async calls. Can I do this flat with promises?

var insertOrUpdateBuilding = (callback)=>{
// Check if building exists
db('buildings')
.where({externalId: buildingId})
.then(function(rows){
// Building exist, do nothing
if(rows){
callback ();
}
// Building does not exist. Insert it
if(!rows){
return db('buildings').insert({externalId: buildingId, name: req.body.name})
}
})
.then(function(promise){

})
.catch(function(err){
callback({message: 'Error looking up building', err: err})
})
};


I'm stuck. How do I proceed?

Answer

Promises are sticky, once you start using them, every involved function will have to accept and return promises as well. In your example, if db() is promised, then insertOrUpdateBuilding should return a promise too, that is, db(...) with some thens attached to it

var insertOrUpdateBuilding = () => db('buildings')
    .where({externalId: buildingId})
    .then(rows => rows ||
        db('buildings').insert({externalId: buildingId, name: req.body.name}))
    ;

and whoever calls insertOrUpdateBuilding should be promised as well:

  insertOrUpdateBuilding().then(okay).catch(error!)

Note that it generally doesn't make sense to catch errors in a lower-level function (except for logging/debugging purposes). Let the error propagate to the upper level where you can handle it in a sensible way, e.g. inform the user.