cyberwombat
cyberwombat

Reputation: 40133

Throwing an error outside of promise flow

I have a method that calls a promised function. Before I call this method, however, I need to perform some validation.

var outerMethod = function(params) {
  if(!params) throw new Error();

  return somePromiseFunction();
}

What is the proper way to throw the first error. I have tried wrapping the entire outerMethod inner content in a new Promise(function(resolve, reject) { }); but that did not quite do the trick;

Upvotes: 0

Views: 336

Answers (1)

danh
danh

Reputation: 62676

You could answer a rejected promise, like this:

var outerMethod = function(params) {
    return (!params)? q.defer().reject(new Error('missing params')) : somePromiseFunction();
}

Style-wise, I'd reverse the condition (params)? /* happy case */ : /* sad case */;, but I left it in the negative since we're talking about the rejection.

Upvotes: 2

Related Questions