Joe
Joe

Reputation: 4254

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?

Upvotes: 0

Views: 61

Answers (2)

georg
georg

Reputation: 215039

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.

Upvotes: 3

Niels Steenbeek
Niels Steenbeek

Reputation: 4834

Try using ES7 async/await.

var async insertOrUpdateBuilding = (callback) => {
    try {
        // Check if building exists
        let rows = await db('buildings')
          .where({externalId: buildingId});
        // Building exist, do nothing
        if (rows){
          callback();
        }
        // Building does not exist. Insert it
        if (!rows) {
          let row = await db('buildings').insert({
            externalId: buildingId, 
            name: req.body.name
          });
          callback();
        }
    } catch (e) {
        callback({message: 'Error looking up building', err: e});
    }
};

Upvotes: 0

Related Questions