Is wrapping a promise in a promise an anti-pattern?

前端 未结 1 1218
既然无缘
既然无缘 2021-01-05 21:01

I was trying to write code for reconnecting to a database with a timeout using a Promise API.

What I ended up doing in the end was wrapping the promise to connect to

相关标签:
1条回答
  • 2021-01-05 21:52

    Here's a slightly more general solution (tests for non-positive):

    function withRetry(asyncAction, retries) {
      if (retries <= 0) {
        // Promise.resolve to convert sync throws into rejections.
        return Promise.resolve().then(asyncAction); 
      }
      return Promise.resolve()
        .then(asyncAction)
        .catch(() => withRetry(asyncAction, retries - 1));
    }
    

    This function will take a function that returns a promise, and a number of retries, and retry the function as many times as retries, if the Promise rejects.

    If it resolves, the retry chains stops.

    In your case:

    let connectionPromise = withRetry(connect, 3); // connect with 3 retries if fails.
    
    0 讨论(0)
提交回复
热议问题