-1

I am working on a piece of code utilizing Promises and I came to the point where I would like to reject a Promise and have some return values. Essentially in some cases it is not enough to reject the Promise blindly. I have to do some extra work based on what client code i.e. Promise catch statement logic decides to return.

Right now it seems reject does not return any value regardless.

Can anyone suggest a workable approach? Is it possible?

This is what I would like to be able to do...updating since I may have caused some confusion...

function executeSomeLogic() {
  return new Promise((resolve,reject) => {
    var err = doSomeWork();
    if (!err) {
       resolve("Finished without error");
    } else {
      // I cannot get this to work. reject does not return a value.
      // ret is always undefined after this next line
      let ret = reject("Return true if you want to roll back"); 
      if (ret) {
        doSomeInternalCleanup();
      }
    }
  });
}

// this runs in completely different place/module/file and simply invokes executeSomeLogic function. Returning anything from catch does not do anything...

executeSomeLogic().then(result => { 
  console.log("all good");
}).catch(error => { 
  // Here, is client code I want to tell the calling code that I want 
  // to clean up ONLY if error message match what I am looking for.
  // Problem is returning anything from catch is not doing anything to 
  // the code that called reject...
  console.log("no good");
  if (error == "Return true if you want to roll back"){
    return true;
  } else {
    return false;
  }
});
Moonwalker
  • 3,462
  • 4
  • 25
  • 31
  • When you reject you send a value, at least an error ! no ? i am not sure that you use Promise as it should be ! [some help](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) – Anonymous0day Nov 04 '15 at 20:27
  • and [this one too](https://www.promisejs.org/) – Anonymous0day Nov 04 '15 at 20:33
  • What is `reject`? Is it the `reject` callback in a `Promise` constructor? Please provide the needed information to grok your code without making us have to guess. – JLRishe Nov 04 '15 at 20:35
  • I updated the example. It is non-working code since I cannot get a return value from reject() but show what I would like to be able to do. – Moonwalker Nov 04 '15 at 20:40
  • maybe you should `doSomeInternalCleanup()` before reject ? no ? and why `let ret` ?? – Anonymous0day Nov 04 '15 at 20:44
  • I think this turns an asynchronous promise into a synchronous function. You may want to refer to http://stackoverflow.com/q/23667086/2336725 The short version is that instead of `return`ing, you should take the appropriate action within the promise. – Teepeemm Nov 04 '15 at 20:46
  • @Anonymous0day - because I do not want to cleanup unconditionally. Imagine a transaction where each step can fail, but individual failure does not have to fatal to the whole transaction. So this Promise represents a single step of a bigger transaction (Promise). I want the client code to decide for example if the bigger transaction should be aborted or not. Just an example...ret is supposed to be a return value from reject WHICH I CANNOT GET...and thus my question. – Moonwalker Nov 04 '15 at 20:58
  • @Teepeemm - not what I want to do. I want the client code to drive how the internal cleanup should proceed. And this is not turning async into sync.. – Moonwalker Nov 04 '15 at 21:00
  • You have a misunderstanding of how works Promise. `catch` never go back to or return something to the caller ! – Anonymous0day Nov 04 '15 at 22:33
  • You should read this [very good explanation of Promise](http://www.html5rocks.com/en/tutorials/es6/promises/) i think it will help you to understand and find a way to resolve your issue. – Anonymous0day Nov 05 '15 at 08:25
  • :) I know it doesn't...that is why I wrote the original post asking for expert help and highlighted where I am hitting the wall (reject and catch)... – Moonwalker Nov 05 '15 at 08:28
  • @Anonymous0day - I think I have a pretty good handle of Promises, I can't help if you can't understand the problem. – Moonwalker Nov 06 '15 at 00:30
  • @Moonwalker you are wrong ! first i don't need help, second you don't understand how promises works, third i can't understand your problem because there is no problem, only misunderstanding from you *(see second point)* and at last have you read from the link i provide you ? – Anonymous0day Nov 06 '15 at 01:15

2 Answers2

0

You are saving the Promise object in the ret variable, not the value...

Try: reject('Hello Boy').then(null, function(greetingsError) { console.log('error is', greetingsError); })

Hitmands
  • 13,491
  • 4
  • 34
  • 69
-1

One test case could be :

let ret = Promise.reject( 'my rejected Value' );
ret.then(
  val => {console.log('fulfilled val :' , val);return val;}  ,
  val => {console.log('rejected val :' , val);return val;}
).then(
  rep => console.log('response : ' , rep)
)

To have a better understanding i added some console.log to your code.
(see also the comments)

function executeSomeLogic() {
  return new Promise((resolve,reject) => {
    var err = doSomeWork();
    
    // this part below  is never reached
    // never executed because doSomeWork() don't exists
    
    console.log('we pass here');
    
    if (!err) {
       resolve("Finished without error");
    } else {
      var ret = reject("Return false if you want to roll back");
      if (ret) {
        console.log(' i need to doSomeInternalCleanup()');
        doSomeInternalCleanup();
      }
    }
  });
};




executeSomeLogic().then(result => { 

  // We Go directly to the catch  
  
  console.log("all good");

}).catch(error => { 
  
  console.log("no good");
  console.log(error); // ---> ReferenceError: doSomeWork is not defined
  
  if (error == "Return false if you want to roll back"){
    console.log('true');
    return true;

  } else {
  
    console.log('false'); // ----> this is printed
    return false;
  }
});

To have your behaviour test this piece of code :

//console.clear();
function doSomeWork() { 
  //return Boolean(Math.floor( Math.random() * 2));
  return true;
};


function executeSomeLogic() {
  return new Promise((resolve,reject) => {
    var err = doSomeWork();
    
    
    console.log('we pass here');
    
    if (!err) {
       resolve("Finished without error");
    } else {
      var ret = reject("Return false if you want to roll back");
      
      console.log('we have rejected' , ret);
      if (ret) {
        // never reached because reject don't return something !
        console.log('because i have ret i need to doSomeInternalCleanup()' , ret);
        //doSomeInternalCleanup();
      }
      
      console.log('but i can doSomeInternalCleanup() even without ret' ,ret);
      
    }
  });
  
   
  
};




executeSomeLogic().then(result => { 

  // We Go directly to the catch  
  // but if you had returned something valid like 'cleanupDone'
  // the value of result would be 'cleanupDone'
  
  console.log("all good");

}).catch(error => { 
  
  console.log("no good");
  console.log(error); // ---> "Return false if you want to roll back"
  
  if (error == "Return false if you want to roll back"){
    console.log('true'); // ----> this is printed
    return true;

  } else {
  
    console.log('false'); 
    return false;
  }
});
Anonymous0day
  • 3,012
  • 1
  • 14
  • 16
  • i gave example with both the Running promise and client code that triggers this promise. I cannot see how your answer plays into the pattern I described. – Moonwalker Nov 04 '15 at 21:02
  • @Moonwalker i updated my answer to reflect your need ! – Anonymous0day Nov 04 '15 at 21:24
  • not sure what you mean by "this part below in never reachd never executed"...it actually is executed all the time...apologies but i can't see how you code does what I am looking for.. – Moonwalker Nov 04 '15 at 21:56
  • @Moonwalker : have you run it ??? if you have an error `var err=doSomeWork()` the error is raised immediately not later so the code after this line is never reached or executed ***in error case*** ! just try this : `var err=doSomeWork(); alert(err);` tell me if you can see the alert box ! – Anonymous0day Nov 04 '15 at 21:59
  • of course I can. doSomework is a synchronous function. it returns an some code ,maybe true/false. this does not stop the code from executing..it runs all the way down to completion. – Moonwalker Nov 04 '15 at 22:06
  • @Moonwalker ha ok ! i was not aware ! i have to guess that :-) i will update my code ! – Anonymous0day Nov 04 '15 at 22:10
  • in your answer sample...of course you can see the false/true printed inside the catch, where you have /// this is printed. The issue is the your returning true/false from catch does NOTHING and ret is ALWAYS undefined after var ret = reject(...) – Moonwalker Nov 04 '15 at 22:18
  • I have updated my code ! but reading your last comment i have a doubt about my understanding of your need or your understanding of Promise ! – Anonymous0day Nov 04 '15 at 22:24