Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
88 views
in Technique[技术] by (71.8m points)

javascript - How can I know the promise function calling is caught exception or not

I have two simple function as below, one is callback and another one is Promise, in call back function, I can know whether the function caller caught the exception, but in the promise function I don't know how to handle it.

First one

  let call = function(a,b,success,fail){
      if(a==b){
         success();
       }
      else{
         if(fail){
           fail();
         }
         else{
           alert("a is not equal b");
         }
       }
  }

The second one

   let call = function(a,b){
     return new Promise(resolve,reject){
        if(a==b){
          resolve();
        }
        else{
           //I want to code here, if the call is not catch error, 
           //the system alert("a is not equal b"), otherwise call the reject.           
        }
     }
   }
question from:https://stackoverflow.com/questions/65912517/how-can-i-know-the-promise-function-calling-is-caught-exception-or-not

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no good way to know whether the caller is handling a promise rejection. There are hacks that work in some circumstances, but I would not suggest going there.

ALL promises require that the caller handle any possible rejections - it is not optional. That is the law with promises. That's part of the contract for using your API. That's not your API's responsibility itself to try to make up for a client writing bad code and promises are not designed to make that feasible.

So, it's not an option for you to change your function's behavior based on whether a promise rejection is or isn't being handled.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...