typescript for循环中的多个等待(循环中无等待)

js4nwp54  于 2023-01-21  发布在  TypeScript
关注(0)|答案(1)|浏览(236)

我有一个函数,我禁用了eslint警告,但我想改进代码。我知道我应该使用promise.all(),但我不确定如何继续,因为我在for循环中有两个wait。

const getBatchLogsByHash = async (
  chainId: number,
  rpc: string,
  batch: BlockRange,
) => {
  const firstBlock = batch.startBlock;
  const lastBlock = batch.endBlock;
  const logs: Array<Log> = [];
  /* eslint-disable no-await-in-loop */
  for (let i = firstBlock; i <= lastBlock; i += 1) {
    const block = await ethers.fetchBlock(chainId, rpc, i);
    const blockLogs = await ethers.fetchLogsByBlockHash(
      chainId,
      rpc,
      block.hash,
    );
    logs.push(...blockLogs);
  }
  return logs;
};

谢谢你的帮助

nvbavucw

nvbavucw1#

您可以在promise执行器中使用await,以便在解决promise之前等待。然后,Promise.all允许您并行执行lastBlock - firstBlock + 1ethers操作。由于它们 * 完成 * 的顺序无法预测,您不能使用logs.push(...blockLogs)。请改用concat,以便按照您 * 开始 * 这些承诺的顺序连接各个承诺解析到的blockLogs

var promises = [];
for (let i = firstBlock; i <= lastBlock; i += 1)
  promises.push(new Promise(async function(resolve, reject) {
    const block = await ethers.fetchBlock(chainId, rpc, i);
    const blockLogs = await ethers.fetchLogsByBlockHash(
      chainId,
      rpc,
      block.hash,
    );
    resolve(blockLogs);
  }));
var logs = Array.prototype.concat.call(...await Promise.all(promises));
return logs;

但是下面使用.then的简单代码是等效的:

var promises = [];
for (let i = firstBlock; i <= lastBlock; i += 1)
  promises.push(ethers.fetchBlock(chainId, rpc, i).then(
    block => ethers.fetchLogsByBlockHash(
      chainId,
      rpc,
      block.hash,
    )
  ));
var logs = Array.prototype.concat.call(...await Promise.all(promises));
return logs;

相关问题