qwest icon indicating copy to clipboard operation
qwest copied to clipboard

Function parameters anti-pattern

Open csimi opened this issue 9 years ago • 8 comments

Right now the parameters are passed to the handler functions like this:

function(xhr, response)

Isn't this a promise anti-pattern? I have to use intermediate functions to get the response instead of directly manipulating it like:

qwest.get('/someArrayResource')
         .then(_.first)
         .then(doWhatever);

Having the XHR object as the primary parameter in the function would be useful only in a few situations, where for example you care more about the status code instead of the response, which only happens rarely.

csimi avatar Jun 28 '16 11:06 csimi

You're right. response should be the first parameter, and xhr should be available with this keyword. I'll plan this for a future major release of qwest. Unless you really need this ASAP, I'll release it in the next months.

pyrsmk avatar Jun 30 '16 09:06 pyrsmk

This will mess up es6 arrow functions.

this.products = [];

quest.get(....)
.then((xhr, response) => {
   this.products = response.products;
});

:/

phillip-haydon avatar Jul 06 '16 10:07 phillip-haydon

Hum, indeed... What would you suggest?

pyrsmk avatar Jul 06 '16 11:07 pyrsmk

Personally I think the API is fine, but if it were to change, just swap the args around.

(response, xhr) effectively makes xhr optional, keeps the response the main thing the user wants/needs, doesn't mess with any scoping in ES5/6

Sometimes anti-patterns are necessary. (not that I consider this an anti-pattern to begin with)

phillip-haydon avatar Jul 06 '16 11:07 phillip-haydon

Indeed, It seems the best way to do it. I plan this change for a future major release then. I need to refactor qwest's code a bit, it's kinda messy ^^

pyrsmk avatar Jul 07 '16 10:07 pyrsmk

Sorry this question is only slightly related but I didn't find the answer in the docs.

If I have:

qwest.get(...)
    .then(function (response, xhr) {
        return "whatever";
    })
    .then(function (???) { ... });

The first then returns a promise that is resolved with "whatever", right? So, have I lost xhr at this point? Is there any way to get xhr in subsequent promises?

okonomiyaki3000 avatar Aug 19 '16 01:08 okonomiyaki3000

You're right, at this point xhr is lost. But I can make some method to get it anyway... I should investigate this ^^

pyrsmk avatar Aug 19 '16 08:08 pyrsmk

It's pretty easy to keep the xhr but you're getting into pyramid territory. Return a new promise chain.

qwest
    .get(...)
    .then(function (response, xhr) {
        return Promise
            .resolve(response)
            .then(function (???) {
                ...
            });
    });

csimi avatar Aug 19 '16 09:08 csimi