Are there any (negative) side effects when I don't use the “then” function of a Promise?

前端 未结 1 889
别跟我提以往
别跟我提以往 2021-01-18 00:17

I have a function which returns a Promise.

Now, sometimes it makes sense for the consumer to use the \"then\" function on that Promise. But sometimes the consumer si

相关标签:
1条回答
  • 2021-01-18 00:54

    Remember that every call to then results in a new promise. So any Promise implementation that had a memory leak as a result of a promise not having any resolution handlers attached would be a broken implementation, what with all those promises that we never hook handlers to being returned. I very much doubt implementations of ES2015's promises, Bluebird, Q, etc. have that behavior.

    Separately, as conceptually a promise's resolution handlers are basically just functions stored by the promise and then called when appropriate, it's not likely to be a memory leak if you never give it any functions to store.

    But, there is a problem with your fire-and-forget, just not a memory leak problem: It breaks one of the main Promise rules: Either handle rejection, or return the promise chain to something else that will handle rejection. Since you're not doing that, if the operation fails, you'll have an unhandled rejection. Unhandled rejections are reported to the console and in some environments may terminate your app (at some point, Node.js may start terminating the process when this happens, see this open issue).

    If the fact that then returns a new promise is a surprise, consider:

    let p1 = new Promise(resolve => {
      setTimeout(() => {
        resolve('a');
      }, 100);
    });
    let p2 = p1.then(result => {
      console.log("p1.then got " + result);
      return 'b';
    });
    p2.then(result => {
      console.log("p2.then got " + result);
    });

    which outputs

    p1.then got a
    p2.then got b
    
    0 讨论(0)
提交回复
热议问题