1

I'm working with promises and need to figure out how to properly chain them, i understand how it works if promises either resolve on success and reject on error, but what if there can be an error state after one of the promises resolves?

Here is my scenerio

function getUser(userId){...} 
// resolves if user exist and (activated or not) returning user
// rejects to error1: user does not exist

function doTask(user){...}
// resolves on successful completion of the task
// rejects error3: could not do Task

what if i want to make another promise do task with user id, but only if the user is activated

// function doTaskWithUserId(userId)
// reject to error1; user does not exist
// reject to error2; if user is not activated
// reject to error3; could not do task

here is what i can do, but if feels like I am messing somthing; But this seems to be a promise anti-pattern

function doTaskWithUserId(userId){
    var deffered = q.defer();
    getUser(userId)
    .then(function(user){
        if(user.activated === true){
            return doTask(user);
        }else{
            deffered.reject(error2); // user is not activated
        }
    }, function(){
        deffered.reject(error1);  // user does not exist
    })
    .then(function(){
        deffered.resolve(); // task complete
    }, function(){
        deffered.reject(error3) // could not do task
    })
    return deffered.promise;
}

It seems that if I do it this way the outer promise is hung up, i've read about the .fail() and .catch methods but can seem to wrap my head around them. Anything helps! thanks

Aaron
  • 2,450
  • 1
  • 17
  • 23

1 Answers1

4

But this seems to be a promise anti-pattern

It is indeed: The deferred antipattern! You don't need to construct a new deferred, you can just chain your actions, mappings and errors using then. You'll simply reject the returned promise by throwing:

function doTaskWithUserId(userId) {
    return getUser(userId).then(function(user) {
//  ^^^^^^
        if (user.activated) {
            return doTask(user);
        } else {
            throw error2; // user is not activated
        }
    }); // .then() returns a promise, which we return from the function
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375