search

Home  >  Q&A  >  body text

javascript - A question about promise exception catching, please give me an answer

I am new to promises and there is something I don’t understand. I would like to ask you for help. :

The code is as follows. My question is why I hand-written an undefined error in the timer, which will cause the console to directly report an error, instead of saying rejection and outputting 2? And if I reject() directly , the console will not report an error, and it is normal if you write by hand outside instead of inside the timer. (Here b is an undefined variable)

var p = new Promise(function(resolve, reject) {
    setTimeout(function () {
        b++;
    },1000);
    //b++;
});
p.then(function(){
    console.log(1);
},function(){
    console.log(2);
});

According to the above, the console reports an error.

According to the following words, the rejection will be captured and output 2

var p = new Promise(function(resolve, reject) {
    
    b++;
});
p.then(function(){
    console.log(1);
},function(){
    console.log(2);
});
过去多啦不再A梦过去多啦不再A梦2767 days ago659

reply all(1)I'll reply

  • 黄舟

    黄舟2017-06-12 09:30:47

    Because the b++ error is in the setTimeout function, not in the promise function.

    reply
    0
  • Cancelreply