簡體   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