【问题标题】:Why async/await doesn't synchronizes ioredis get method execution inside a forEach loop?为什么 async/await 不同步 ioredis get 方法在 forEach 循环中的执行?
【发布时间】:2019-06-06 13:09:17
【问题描述】:

Async/Await 方法:

Ids = ['abc','lmn','xyz']

Ids.forEach(function (resId){
    console.log('inside loop');
    async function operation(){
        var curObj = await redisClient.get('key1');
        console.log('done waiting');
  }
}

另一个函数的回调方法:

function operation(cb) {
         redisClient.get('key1', cb);
       }
operation(function(){
    console.log('inside operation');
});

我想等到 curObj 变量设置并按顺序执行代码以打印“完成等待”。我使用了 async/await,但它似乎没有按预期工作。然后我用相同的get方法使用回调仍然相同。我使用 ioredis 库。

我做错了什么?

【问题讨论】:

    标签: node.js async-await ioredis


    【解决方案1】:

    Async/await 方法应如下所示:

    (async() => {
      const Ids = ['abc','lmn','xyz'];
    
      const operation = async (){
       var curObj = await redisClient.get('key1');
       console.log('done waiting');
      }
    
    
      for (const resId of Ids){
       console.log('inside loop');
       await operation();
      }
    })()
    

    forEach 循环中没有async,但您可以将它与for...of 一起使用。
    注意,我使用 IIFE 函数只是为了举例说明如何在没有其他上下文的情况下使用 async/await。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 2017-10-26
      • 2021-03-21
      • 1970-01-01
      相关资源
      最近更新 更多