Wednesday, 15 March 2017

Break out of Bluebird promise chain in Mongoose

I've studied several related questions & answers and still can't find the solution for what I'm trying to do. I'm using Mongoose with Bluebird for promises.

My promise chain involves 3 parts:

  1. Get user 1 by username

  2. If user 1 was found, get user 2 by username

  3. If both user 1 and user 2 were found, store a new record

If either step 1 or step 2 fail to return a user, I don't want to do step 3. Failing to return a user, however, does not cause a database error, so I need to check for a valid user manually.

I can use Promise.reject() in step 1 and it will skip step 2, but will still execute step 3. Other answers suggest using cancel(), but I can't seem to make that work either.

My code is below. (My function User.findByName() returns a promise.)

var fromU,toU;
User.findByName('robfake').then((doc)=>{
        if (doc){
            fromU = doc;
            return User.findByName('bobbyfake');
        } else {
            console.log('user1');
            return Promise.reject('user1 not found');
        }       
    },(err)=>{
        console.log(err);
    }).then((doc)=>{
        if (doc){
            toU = doc;
            var record = new LedgerRecord({
                transactionDate: Date.now(),
                fromUser: fromU,
                toUser: toU,
            });
            return record.save()
        } else {
            console.log('user2');
            return Promise.reject('user2 not found');
        }

    },(err)=>{
        console.log(err);
    }).then((doc)=>{
        if (doc){
            console.log('saved');
        } else {
            console.log('new record not saved')
        }

    },(err)=>{
        console.log(err);
    });



via fredrover

No comments:

Post a Comment