4

This may well be some newbie thing about JS and or Mithril that I am unaware of, but I have written a caching wrapper around Mithril's m.request() to track multiple pending requests with the intention of coalescing multiple identical requests (which concept fits very well with the backend RESTful API).

My wrapper function is this:

function sendRequest(sdrcfg,rqscfg) {
    var key=JSON.stringify(rqscfg);
    var ret=sdrcfg.cache[key];

    if(!ret) {
        var cleanup=function(dta) {
            delete sdrcfg.cache[key];
            sdrcfg.removed(key);
            if(Object.keys(sdrcfg.cache).length==0) { sdrcfg.completed(key); }
            return dta;
            };

        ret=m.request(rqscfg).then(cleanup,cleanup);

        if(Object.keys(sdrcfg.cache).length==0) { sdrcfg.activated(key); }
        sdrcfg.cache[key]=ret;
        sdrcfg.added(key);
        }
    return ret;
    }

The problem I am having is that when the .then(cleanup,cleanup) clause is present, any errors from the host are received by the success function of all subsequent then() clauses chained to the request with the net effect of converting a failure response to a success response for the downstream code.

If I simply comment out the then clause above, then the application code has the success or failure function called as expected.

It seems like a really straight-forward thing to want to do, and completely in line with Leo's example, but I am stumped. JS and, in particular, promises are new to me, so I don't know exactly how to use them, or if this is expected -- I am just following examples and trying to build on them.

Where am I going wrong with this?

Lawrence Dol
  • 63,018
  • 25
  • 139
  • 189

1 Answers1

3

You should probably be doing:

.then(cleanup, function(e) {
  cleanup()
  throw e; //re-reject for downstreams
})

Promise rejection is similar to a catch block, so once add a callback to handle it, it triggers the resolve callback for the rest of the chain.


Effective from Mithril 0.1.22, programmer Errors (like ReferenceError) are logged to the console if not handled. This reverts to the behavior of 0.1.19.

Lawrence Dol
  • 63,018
  • 25
  • 139
  • 189
LeoHorie
  • 1,320
  • 11
  • 11
  • 1
    Well that makes sense. Did I miss this in your example, or does the example in the ["Wait for it" blog entry](http://lhorie.github.io/mithril-blog/wait-for-it.html) have the same fault? – Lawrence Dol Sep 23 '14 at 22:27