2

Given I have a rejected promise:

var promise = new Promise(function(resolve, reject) {
  reject({error_message: "Foo"});
});

And I want to transform that promise (in that case: extract the error message):

var new_promise = promise.then(function(response) {
  return response.id;
}, function(error) {
  return error.error_message;
});

When I run that promise again:

new_promise.then(function(id) {
  console.log("Object created: "+id);
}, function(message) {
  console.log("Error: "+message);
});

I'll always get Object created: Foo on the console. It seems like the transformation turns the rejected promise into a resolved promise.

Is there a way to transform a rejected promise so the result is another rejected promise?

iblue
  • 29,609
  • 19
  • 89
  • 128

2 Answers2

3

Given I have a rejected promise:

var promise = new Promise(function(resolve, reject) {
  reject({error_message: "Foo"});
});

Notice this should read just var promise = Promise.reject({error_message: "Foo"}); - no complicated constructor needing to be involved here.

And I want to transform that promise

Specifically, you want to map over the error state of the promise. Unfortunately, there is no such method (such as mapError) on standard promises. What you have done in your code

var new_promise = promise.then(…, function(error) {
  return error.error_message;
});

is actually setting up a handler for the error, not a transformation. You "catch" the error and then return a new result - see also this control flow graph.

Is there a way to transform a rejected promise so the result is another rejected promise?

Yes, you need to get a rejection as the result of your handler. You can do that by either

.then(…, function(error) {
    return Promise.reject(error.error_message);
})

or by

.then(…, function(error) {
    throw error.error_message;
})

(however, notice that it is frowned upon not to reject promises with actual Error objects)

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

instead of:

return error.error_message;

you could use:

throw error.error_message;
iblue
  • 29,609
  • 19
  • 89
  • 128
kapejod
  • 96
  • 1