猿问

自定义重试功能

尝试创建一个retry返回函数的函数,该函数调用回调函数并从传递其参数的回调函数返回值并捕获错误。如果捕获到错误,它应该返回带有 catch 的回调函数。如果错误数超过计数,则抛出错误。


这是到目前为止所做的:


const retry = (count, callback) => {

    let attempts = 1;

    const _retry = async (...args) => callback(...args)

        .catch(err => {

            if (attempts > count) throw err

            attempts++

            return _retry(...args)

        });

    return _retry

}

调用时出现问题:


var r = Math.random().toString(36).slice(2)

var arg = (n) => async (...v) =>

    --n < 0 ? v : Promise.reject(Error(`>>> x:${v}`))

    

await retry(3, arg(2))(r)


莫回无
浏览 72回答 1
1回答

慕后森

由于 async 关键字,在我看来重试现在会返回一个 Promise。尝试从重试定义中删除 async 关键字并使 _retry 函数异步:const retry = (count, callback) => {&nbsp; &nbsp; let attempts = 1;&nbsp; &nbsp; return _retry = async (...args) => callback(...args)&nbsp; &nbsp; &nbsp; &nbsp; .catch(err => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (attempts > count) throw err&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; attempts++&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return _retry(...args)&nbsp; &nbsp; &nbsp; &nbsp; });}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答