【问题标题】:npm 'p-queue' and Generator function instead of async/awaitnpm 'p-queue' 和 Generator 函数而不是 async/await
【发布时间】:2020-02-22 02:17:09
【问题描述】:

是否可以在内部使用生成器而不是 async/await 函数 queue.add(...)?

而不是这个(它有效):

queue.add(async () => {
   await Api.getSomeInfo() 
})

我需要使用这样的东西(它不起作用):

queue.add(function* () {
   yield Api.getSomeInfo() 
})

【问题讨论】:

    标签: javascript react-native generator yield


    【解决方案1】:

    根据您的需要,您可以编写辅助函数来将生成器转换为异步函数,类似这样

    const toAsync = (generator) => async () => {
      let g = generator()
      let result = g.next();
      while (!result.done) {
        const val = await result.value
        console.log(val)
        result = await g.next();
      }
    }
    
    const delay = (arg) => new Promise(r => setTimeout(() => r(arg),1000))
    
    queue.add(toAsync(function* myGenerator() {
      for (let i = 0; i < 5; i++) {
        yield delay(i)
      }
    }))
    

    【讨论】:

      猜你喜欢
      • 2020-10-15
      • 2021-08-06
      • 2019-02-17
      • 2020-09-22
      • 1970-01-01
      • 2023-03-10
      • 2020-09-25
      • 2018-12-23
      • 2021-03-10
      相关资源
      最近更新 更多