Throwing an error will automatically reject the Promise
. Read more about it here
But there is something to discuss about. Look at the following code. The code throw an error.the error is thrown from the inside of a promise. It will automatically rejected and initiate the catch chain.
function test(value){
return new Promise(function (fulfill, reject){
throw e;
});
}
test('sample text').then(result=>console.log(result)).catch(result=>console.log(result))
But what if I've used a Web API e.g setTimeout()
inside my promise. Look at the following code:
function test(value){
return new Promise(function (fulfill, reject){
setTimeout(function(){
throw new Error('haha');
},1000)
});
}
test('sample text').then(result=>console.log(result)).catch(result=>console.log(result))
Web APIs are asynchronous. Whenever a Web API is called from inside a promise, the JavaScript engine take that async
code outside for execution. In simpler words, web APIs or asynchronous code gets executed outside of the main call stack.
So, throwing an error from setTimeout()
won't have any reference of the caller promise, thus can't initiate the catch
block. You need to reject()
it from setTimeout()
to initiate the catch
block if there is any error.
Will it cause a memory leak?
Answer: no
the test().then().catch()
will be garbage collected as soon as it finished executing. But if you would've kept the promise in a global variable like var p = test(); p.then().catch()
then the variable p
will stay in memory, it won't be garbage collected. But that's not a memory leak. Memory leak is a completely different aspect and doesn't apply in this kind of scenario.