Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

Javascript中,如何将函数嵌套函数的函数封装写的更优雅?例如:

function checkOrderStatus(n){
    var checkIndex=0;
    function loop(n){
        setTimeout(function (){
        checkIndex++;
        $http.get('/get/status', {}).then(function (res) {
            if (res.success) {
                 if(checkIndex<n){
                     loop(n)
         
                    } 
                } 
         }) 
         },500);
       }
    loop(n);
}

这个函数的功能是每隔500ms去请求一下后台接口,这里我要用checkIndex这个变量累加去计算执行次数,但感觉这个封装的不太优雅,有哪位大神指点一下没


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
// 封装
    const useRet = (fn, n, time) => {
      return function() {
        setTimeout(async () => {
          const success = await fn(...arguments);
          if (success && n > 1) useRet(fn, n - 1, time)(...arguments);
        }, time);
      };
    };

    const test = () => {
      return new Promise(resolve => {
        resolve({ success: true });
      });
    };

    const fn = async a => {
      console.log(a); //'传一个参数'
      return await test().then(({ success }) => success);
    };
    // 使用
    const ret = useRet(fn, 5, 1000);
    // 执行
    ret("传一个参数");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...