Per Ström Per Ström - 10 months ago 56
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
.where({externalId: buildingId})
// Building exist, do nothing
callback ();
// Building does not exist. Insert it
return db('buildings').insert({externalId: buildingId, name:})

callback({message: 'Error looking up building', err: err})

I'm stuck. How do I proceed?

Answer Source

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:}))

and whoever calls insertOrUpdateBuilding should be promised as well:


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.