0

Check the following code, why the error cannot be caught by promise

var promise = new Promise(function(resolve, reject) {
resolve("ok");
setTimeout(function() { throw new Error('test') }, 0)
});
promise.then(function(value) { console.log(value) }).catch(error=>console.log("got an error"));

It won't display got an error. However, if I directly use Throw new Error('test'), it will be caught. Can someone please explain why?

Jinxin Ni
  • 331
  • 3
  • 10
  • A promise can **either** resolve or reject. If it's already resolved, that's it - it won't then reject. – Aurora0001 Nov 27 '16 at 20:37
  • Also you never call reject. But you could do this: `promise.then(function(value) {throw new Error('test')}).then(...).catch(...)` – Tesseract Nov 27 '16 at 20:38
  • @SpiderPig what's the difference between use setTimeout and directly throw new Error that cause setTimeout Error won't be caught? – Jinxin Ni Nov 27 '16 at 20:49
  • @Aurora0001 yes I agree with your point but my question is if you directly use throw new Error(), it will be caught. – Jinxin Ni Nov 27 '16 at 20:52
  • 2
    How is the promise supposed to know that the error was thrown? The function you pass into setTimeout is not run by the promise. – Tesseract Nov 27 '16 at 20:53
  • @SpiderPig that's resonable. Thanks. I figured the same reason too but I just want to see if I can have some deep thoughts of what promise is. – Jinxin Ni Nov 27 '16 at 20:55
  • One way to deeply understand how a promise works is to implement your own promises. Here is an example: http://pastebin.com/Z8dh4YhL – Tesseract Nov 27 '16 at 21:47

0 Answers0