weixin_33725807 2016-07-28 11:36 采纳率: 0%
浏览 24

如何做出递归承诺

I want to add retry logic to my javascript HTTP service, which internally uses Axios and returns promises. Goal is to retry fetch/post until it resolves or retry limit is exceeded. I came up with this draft (not working as it is)

fetchSomething(numRetry) {

        if (!numRetry)
            numRetry = 0

        return new Promise(function(resolve, reject) {
            axios.get('/services/rest/vopa/sanomaloki/virheet')
                .then(response => resolve(response))
                .catch(response => {
                    if (numRetry > FETCH_RETRY_LIMIT)
                        reject(response)
                    else
                        return fetchSomething(numRetry + 1)
                })
        });
    }

As far as I know, calling fetchSomething in catch creates new resolve and reject functions, but I would like it to resolve or reject the original promise

  • 写回答

2条回答 默认 最新

  • weixin_33735676 2016-07-28 12:14
    关注

    How about this simpler version (untested!):

    function fetchSomething(numRetry = 0) {
        return axios.get('/services/rest/vopa/sanomaloki/virheet')
            .catch(response => {
                if (numRetry > FETCH_RETRY_LIMIT)
                    return Promise.reject(response); // pass it on
                else
                    return fetchSomething(numRetry + 1); // might work
            });
    }
    
    评论

报告相同问题?