This was originally a question about the Worklight documentation, it transpires that my real question is about JQuery's Deferred/Promise API and the promise.then() function.
Context:
The documentation for the 5.0.6 JsonRestStore API gives examples of using the new Promise capability offering two possible formulations.
someFunction.then(
successCallback,
errorCallback,
optionalProgressCallback);
And
someFunction().then(successCallback).fail(errorCallback)
These two approaches seem, as comments and answers state, effectively the same.
My puzzle is that the JQuery documentation states that then() returns a "new promise".
hence in the second case we are coding:
var p1 = someFunction();
var p2 = p1.then(successCallback);
p2.fail(errorCallback);
I've also seen folks set up a "chain" of actions like this:
someFunction().then(action2).then(action3).then(action4);
setting up a chain of asynchronous actions. So my question becomes what is the relationship between the promises p1 and p2 in the example above. How does that relate to the chain idea?
--- edited to reference the answer ---
Thanks to cnandreu: the key point is that "errors are propagated down a promise chain until an error handler is found." The answer is explained nicely here.
They are functionally the same, this is basically how chaining works right? You have 2 choices, either take the output of one call, and chain it to the next call, or you can save the result in a named variable, and then call the next operation on that named variable.
versus
Promises are a way of handling asynchronous code, here's a quick video and article that explains them.
someFunction()
is going to do an async task, when it finishes it (i.e. gets resolved) it executes thesuccessCallback
and if that fails (ie. is rejected) it executes theerrorCallback
. The relationship is thatp2
is a promise that will get executed only whenp1
gets rejected. Think ofp1.then(win, fail)
andp1.then(win).fail(fail)
as two ways of writing the same thing.The original question was probably referring to the following:
from the JSONStore Documentation. The documentation is specific to the JSONStore API, we refer readers to the jQuery documentation to learn about how promises work in general (see jQuery's API documentation for more details.).
Here's an example:
The output is:
If we switch to
.then(success, failure)
:We get the same output:
Mix them, pick one or use the deprecated callbacks. All JSONStore examples in the documentation should work as expected. Please update your question with real citations from the documentations and a real example showing that the documentation is wrong and I will update my answer. If it turns out something is wrong, I will do everything possible to fix it.