serbanghita serbanghita - 4 months ago 13
Javascript Question

Promises cancel method. Why it's not implemented yet as opposed to other Promises frameworks?

I'm new to promises in JavaScript but straight out the bat I've noticed that if you use a promise implementation other than the one the browser provides, there are some differences ... and the one that stands out is

Promise.cancel
method.

This is visible when you're using chained promises:

myPromise.then(this.view.firstMethod)
.then(this.view.secondMethod) // Fails, need to cancel the chain!
.then(this.view.thirdMethod)
.then(this.view.fourthMethod);


Using
WinJS.Promise
to cancel chained promises: https://jsbin.com/tuviqi/edit?js,console correctly shows in console:

0
1


Using
Promise
object from browser to cancel the same chained promises: https://jsbin.com/morazi/edit?js,console and shows

0
1
"Error in secondMethod."
undefined


I've also tried using
catch
which is ES6 sugar: https://jsbin.com/goqixal/edit?js,console - but is get:

0
1
"Error in secondMethod."
undefined <--- jsbin doesn't show this, look into console


I browsed into https://github.com/promises-aplus/cancellation-spec/issues/1 - but it's not clear to me why this is stalled.

When using
Promise
from browser am I suppose to chain 1, 2 and inside 2 chain 3, 4?

Answer

You're confusing "cancelling" a promise and "rejecting" a promise.

The two cases you show are different in one important regard, which is that in the second, you are providing a rejection handler on the third branch:

.then(this.view.thirdMethod, function(error) { console.warn(error); })
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Once this rejection handler executes, unless you re-throw the error, the chain goes back onto the "success" path, which causes the fourth branch to execute. However, since you return nothing from the rejection handler, the value passed to the fourth handler is undefined, which is why that is being logged to the console.

"Cancelling" promises is a separate, complex topic which is under consideration by the ES language group. One proposal is here.