async await 的妙用

面试题:有一个url数组,var urls = [‘/a’, ‘/b’, ‘/c’,…],要求依次请求这几个url, 要求是 第一个请求完了才发第二个请求,第二个完了才发第三个请求,如此依次。

async doFuc(db) {
    let urls = ['/a', '/b', '/c'];
    for (let doc of urls) {
        await db.post(doc);
    }
}

面试题:定义这样一个函数
function repeat(func, times, wait) {},参数分别是需要 repeat的函数, repeat的次数,每次repeat的间隔,使用方式如下:调用这个函数能返回一个新函数,,比如传入的是alertvar repeatedFun = repeat(alert, 10, 5000);调用返回的这个新函数,如:repeatFun(“hellworld”);会alert十次 helloworld

    function repeat(func, times, wait) {
      if (!window.count) {
        window.count = 0
      }
      if (times <= 0) {
        return;
      }
      setTimeout(() => {
        func()
        times--;
        count++
        repeat(func, times, wait)
      }, count ? wait : 0)
    }
    function repeat(func, times, wait) {
      for (let i = 0; i < times; i++) {
        (function(i) {
          setTimeout((i) => {
            func()
          }, wait * i)
        })(i)
      }
    }
    async function repeat(func, times, wait) {
      for (let i = 0; i < times; i++) {
        await setTimeout(() => {
          func()
        }, wait * i)
      }
    }
    function fun1() {
      console.log(2, new Date())
    }
    repeat(fun1, 3, 1000)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值