编辑代码

function retry(fn, times, t) {

    return function (...agrs) {
        var _this = this;
        const dispatch = (cb) => {
            const p = cb.catch(e => {
                if (times) {
                    return new Promise((res, rej) => {
                        setTimeout(() => {
                            res();
                        }, t)
                    }).then(() => {
                        return dispatch(fn.apply(_this, agrs));
                    })

                } else {
                    return Promise.reject('00000');
                }
            });
            times--;
            return p;
        }
        return dispatch(fn.apply(_this, agrs));
    };
}

var retry2 = function (fn, times, delay) {
    var err = null;
    return function (...agrs) {
        var _this = this;
        new Promise(function (resolve, reject) {
            var attempt = function () {
                fn.apply(_this,agrs).then(resolve).catch(function (err) {
                    console.log(`Attempt #${times} failed`);
                    if (0 == times) {
                        reject(err);
                    } else {
                        times--;
                        setTimeout(function () {
                            attempt()
                        }, delay);
                    }
                });
            };
            attempt();
        });
    }
};


var index = -1;
var query = function () {
    index++
    console.log('try:', index);
    return new Promise((res, rej) => {
        setTimeout(() => {
            index === 3 ? res('yes') : rej();
        }, 1000)
    })
}

retry(query, 2, 1000)().then(res => {
    console.log('success:', res);
}).catch(e => {
    console.log('error:', e);
})