1

I just want to ask how should I pass the resolve promise to catch if the value on the resolve is not intended.

e.g.

let prom = getPromise();

prom.then(value => {
    if (value.notIWant) {
        // Send to catch <-- my question is here, I want to pass it on the catch.
    }

    // Process data.
}).catch(err => {
    // Pass the error through ipc using json, for logging.
});

I tried to using throw but the object cant be parsed to json and just got an empty object.

ANSWER:

@BohdanKhodakivskyi first comment below is the answer I want.

@31py answer is also correct but the @BohdanKhodakivskyi solution is much simplier and will render the same result.

zer09
  • 1,507
  • 2
  • 28
  • 48

4 Answers4

6

Simply use throw value;. In your case:

prom.then(value => {
    if (value.notIWant) {
        // Send to catch
        throw value;
    }

    // Process data.
}).catch(err => {
    // Pass the error through ipc using json, for logging.
});

Please also note the difference and limitations between using Promise.reject() and throw which is perfectly described in this question. For example, throw will not work in some async scenarios.

4

You can simply return a rejected promise:

prom.then(value => {
    if (value.notIWant) {
        return Promise.reject('your custom error or object');
    }

    // Process data.
}).catch(err => {
    console.log(err); // prints 'your custom error or object'
});

.catch actually handles any promise rejection in the chain, so if you're returning a rejected promise, the control automatically flows to catch.

31piy
  • 23,323
  • 6
  • 47
  • 67
1

why you just not rethrow the error? throw new Error("something");

0

You can use outside functions to do it:

var processData = function(data) {
   // process data here
}

var logIt = function(data) {
   // do logging here..
}

let prom = getPromise();

prom.then(value => {
    if (value.notIWant) {
        // Send to catch <-- my question is here, I want to pass it on the catch.
        logIt(/*pass any thing*/);
    }

    // Process data.
    processData(data);

}).catch(err => {
      logIt(/*pass any thing*/);
});
Dabbas
  • 3,112
  • 7
  • 42
  • 75
  • Thanks, actually this is what I am doing, but I am trying not to do things twice. I mean writing the ```logIt``` twice. – zer09 Dec 28 '17 at 08:16
  • you gonna write something some where twice, it's either `reject`, or this method `logIt` – Dabbas Dec 28 '17 at 08:27
  • Actually this is what DRY is about, you move the code to shared method and call it many times in different places. – Dabbas Dec 28 '17 at 08:29
  • Yup, I understand you, and I also use that, but there is some scenario that the ```logIt``` cant handle, and need some processing for special cases before it will passed to ```logIt``` method, so I don't want to write does special process in two blocks or create a new method just for that. – zer09 Dec 28 '17 at 08:38