0

I have written a general .js crud object which holds all the methods used to communicate with the server. However I'd like to avoid the repetition of .then and .catch and I would like to abstract that functionality in an external method.

Not sure if what I'm trying to achieve is even possible.

My code below:

all(url, success, fail){
  return new Promise((resolve,reject) => {
    _get(url)
    .then((response) => {
      if (response.status == 200) {
        success.call(this,response);
        return resolve();
      }
    })
    .catch((error) => {
      fail.call(this, error);
      reject(error);
    });
});}, submit, update .....

Wonderland desired result:

all(url, success, fail){
  return new Promise((resolve, reject) => {
    _get(url).handle(args);
  });
}
royhowie
  • 11,075
  • 14
  • 50
  • 67
Enrico
  • 408
  • 6
  • 13
  • 2
    What is the purpose of returning a `new Promise`? Why not just `return _get(url).then(...).catch(...)`, which is already a promise? – Jordan Running May 31 '17 at 21:08
  • That was actually unexpectedly easy. I'm new to promises and I've missed that part. Doing this actually solved my problem, i've put all the .then and .catch logic inside the original promise. Leave the comment as an answer and i'll check it as correct. Thanks – Enrico May 31 '17 at 21:41
  • 1
    Do not edit the title of your question to add a "Solved" label. Instead, if you have solved the issue on your own, post your solution as an answer and accept it. – royhowie May 31 '17 at 22:10

1 Answers1

2

Just avoid the Promise constructor antipattern and callbacks, and you'll be good!

function all(url) {
  return _get(url).then((response) => {
    if (response.status == 200) {
      return response;
    }
    // most likely you want to `throw` an error here?
  });
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Yes, thank You. In my case, `_get`, was just a wrapper for another promise, so I just had to move the _handling_ logic inside it and call it like this: `_get(url, success, fail)` – Enrico May 31 '17 at 22:24
  • You should never pass `success` and `fail` callbacks to a function that returns a promise, though. – Bergi May 31 '17 at 23:31
  • So, instead of calling success and fails function inside the origin promise, i should just return them and handle at the last chain block? – Enrico Jun 01 '17 at 07:42
  • 1
    Yes, always return your promises, and put callback functions in `.then()` on the result of the calls – Bergi Jun 01 '17 at 14:54