jiananshi
jiananshi

Reputation: 456

How to break up a promise in a `then` function

Here, says we got a user signup request, we gotta detect whether the username is already token(let's just assumes the data is valid), and if it is, goes on:

User
    .getByName(name)
    .then(function (user) {
        // if user is not null, which means the username is already token
        if (user !== null) return res.json({errorCode: 1001})
    })
    .then(function() {
        // Oops, the previous return is captcha here
        // how to break the promise and return the request
        var user = new User({
            name: name
        })
    })

Thanks for help

Upvotes: 1

Views: 102

Answers (3)

Waqas Ahmed
Waqas Ahmed

Reputation: 493

Try AS Below. This is the proper way to use promises.

var  when = require('when');


checkUser(name)
  .then(function () {
    var user = new User({
      name: name
    })
  }, function (error) {
    // handle error here
  })
}

var function checkUser(name){

   var deferred = when.defer();

   User.getByName(name,function(user){
     user === null ?
       deferred.resolve() : deferred.reject(new Error('Username alreay token'))
   });

   return deferred.promise;   
}

Upvotes: 0

Leonid Beschastny
Leonid Beschastny

Reputation: 51480

If you can't resolve your promise, you should reject it:

User.getByName(name).then(function(existing) {
    // If user already exists, we should return
    // rejected promise with good rejection reason
    if (existing !== null) return reject {
        message: 'User already exists',
        errorCode: 1001,
        status: 403
    };
    var user = new User({
        name: name
    });
    // ... some staff ..
    return user.save();
}).then(function(user) {
    // ... some other staff ...
    res.json(user);
}).otherwise(function(err) {
    // Something bad happened somewhere in the chain
    res.status(err.status || 400).json({
        message: err.message
        errorCode: err.errorCode
    });
})

In my example I'm using universal rejection handler to send error response to the client, because we should send something no matter what happened.

reject in my example is a function to return rejected promise. Most promise libraries have such function (e.g. when.reject, Q.reject), but you may replace it with build-in throw statement.

Upvotes: 0

CFrei
CFrei

Reputation: 3627

To avoid the call to your second then, you need to make the first then fail. Just add as the last line of function(user) a throw 'User exists' and the next then goes into the reject path, which you didn't have set.

I admit, its an ugly approach, but it would work! ;)

Upvotes: 1

Related Questions