worklight 5.0.6 JsonRestStore, use of Promises

2019-08-29 07:41发布

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.

2条回答
欢心
2楼-- · 2019-08-29 08:14

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.

var str = "   fooo ";
str.trim().indexOf('f');

versus

var str = "   fooo ";
var strTrimmed = str.trim()
strTrimmed.indexOf('f');
查看更多
淡お忘
3楼-- · 2019-08-29 08:39
var p1 = someFunction();
var p2 = p1.then(successCallback);
p2.fail(errorCallback);

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?

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 the successCallback and if that fails (ie. is rejected) it executes the errorCallback. The relationship is that p2 is a promise that will get executed only when p1 gets rejected. Think of p1.then(win, fail) and p1.then(win).fail(fail) as two ways of writing the same thing.

The original question was probably referring to the following:

A promise object is returned after a JSONStore asynchronous operation is called (find, add, remove, and so on). [...] The [JSONStore.add, JSONStore.find, etc.] failure callback, passed as either the second parameter of .then or the first parameter of .fail returns an error object, [...]

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:

var collections = {
        people : {
            searchFields : {name: 'THIS_SHOULD_PRODUCE_AN_ERROR'}
        }
    };

WL.JSONStore.init(collections)

.then(function(res){
    //the code here should not be called because we expect to fail
    console.log(typeof res === 'object' ? JSON.stringify(res) : res);
})

.fail(function(err){
    console.log(err.toString());
});

The output is:

{"src":"initCollection","err":-12,"msg":"INVALID_SEARCH_FIELD_TYPES","col":"people","usr":"jsonstore","doc":{},"res":{}}

If we switch to .then(success, failure):

var collections = {
        people : {
            searchFields : {name: 'THIS_SHOULD_PRODUCE_AN_ERROR'}
        }
    };

var success = function(res){
    //the code here should not be called because we expect to fail
    console.log(typeof res === 'object' ? JSON.stringify(res) : res);
};

var failure = function(err){
    console.log(err.toString());
};

WL.JSONStore.init(collections).then(success, failure);

We get the same output:

{"src":"initCollection","err":-12,"msg":"INVALID_SEARCH_FIELD_TYPES","col":"people","usr":"jsonstore","doc":{},"res":{}}

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.

查看更多
登录 后发表回答