繁体   English   中英

循环内出现意外的“等待”。 (无等待循环)

[英]Unexpected `await` inside a loop. (no-await-in-loop)

我应该如何在循环内等待bot.sendMessage()
也许我需要await Promise.all但我不知道应该如何添加到bot.sendMessage()

代码:

const promise = query.exec();
promise.then(async (doc) => {
    let count = 0;
    for (const val of Object.values(doc)) {
        ++count;
        await bot.sendMessage(msg.chat.id, `💬 ${count} and ${val.text}`, opts);
    }
}).catch((err) => {
    if (err) {
        console.log(err);
    }
});

错误:

[eslint] Unexpected `await` inside a loop. (no-await-in-loop)

如果您需要一次发送一条消息,那么您所拥有的就可以了, 根据 docs ,您可以像这样忽略 eslint 错误:

const promise = query.exec();
promise.then(async doc => {
  /* eslint-disable no-await-in-loop */
  for (const [index, val] of Object.values(doc).entries()) {
    const count = index + 1;
    await bot.sendMessage(msg.chat.id, `💬 ${count} and ${val.text}`, opts);
  }
  /* eslint-enable no-await-in-loop */
}).catch(err => {
  console.log(err);
});

但是,如果发送消息没有要求的顺序,您应该这样做以最大限度地提高性能和吞吐量:

const promise = query.exec();
promise.then(async doc => {
  const promises = Object.values(doc).map((val, index) => {
    const count = index + 1;
    return bot.sendMessage(msg.chat.id, `💬 ${count} and ${val.text}`, opts);
  });

  await Promise.all(promises);
}).catch(err => {
  console.log(err);
});

一旦迭代在大多数情况下没有依赖性,就可以避免在循环内执行await ,这就是eslint在这里警告它的原因

您可以将代码重写为:

const promise = query.exec();
  promise.then(async (doc) => {
    await Promise.all(Object.values(doc).map((val, idx) => bot.sendMessage(msg.chat.id, `💬 ${idx + 1} and ${val.text}`, opts);)
  }).catch((err) => {
    if (err) {
      console.log(err);
    }
  });

如果您仍然要发送一对一的消息,则您的代码没问题,但是 eslint 您一直在抛出此错误

我最近遇到了类似的问题,当我尝试以异步方式运行链中的一系列函数时,我遇到了 linting 错误。

这对我有用......

 const myChainFunction = async (myArrayOfFunctions) => { let result = Promise.resolve() myArrayOfFunctions.forEach((myFunct) => { result = result.then(() => myFunct() }) return result }

当我在 forEach 循环中使用 await 时,我面临同样的问题。 但是我尝试使用递归函数调用来迭代数组。

const putDelay = (ms) =>
    new Promise((resolve) => {
        setTimeout(resolve, ms);
    });

const myRecursiveFunction = async (events, index) => {
    if (index < 0) {
        return;
    }
    callAnotherFunction(events[index].activity, events[index].action, events[index].actionData);
    await putDelay(1);
    myRecursiveFunction(events, index - 1);
};  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM