Does using Promise and not rejecting it cause memory leak? [duplicate]

别说谁变了你拦得住时间么 提交于 2019-12-12 12:57:25

问题


The code goes like this:

function test(value){
  return new Promise(function (fulfill, reject){
     try {
       fulfill(true);
     } catch(e) {
       throw e;
     }
  });
}

My concern is, when you use Promise and throw error instead of reject(e), will this cause a memory leak?

Because for me, throwing an error instead of rejecting it will not reject or exit the error outside promise. The error will just go around inside the Promise. Let me know your opinion.


回答1:


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.




回答2:


This will not cause a memory leak. However, there are differences worth to consider when using one or the other.

  • Unlike throw, reject() will not terminate the control flow. So, if you have code that you want to continue executing after a rejection, you will probably prefer reject().

  • Using throw in nested promises can cause unexpected results. In such cases, it is recommended to use reject().



来源:https://stackoverflow.com/questions/48455070/does-using-promise-and-not-rejecting-it-cause-memory-leak

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!