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
            });
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题