异步查找最高数

Asynchronous finding highest number

我正在寻找一种方法来异步迭代数组并更新变量,最后 return 这个变量。

export const test = async(
...
): Promise<number> => {
let highestAmount = 0;
    for (const entry of entries) {
        const check = async () => {
            let amount = 0
            try {
                newAmount = await getAmount(entry);
            } catch (e) {
                return;
            }
            if (newAmount > amount ) {
                highestAmount = newAmount;
           }
        }
        check()
    }
    return highestAmount;
}

在当前状态下,我只返回 0,因为该函数不等待其完成。 如果 for 内的所有进程都已完成,是否有一种方法可以使函数仅 returns ? 假设 getAmount(entry) 函数需要 1 秒才能完成,然后我必须等待大约 entries.length 秒。我试图找到一种在 1 秒内执行此操作的方法,因此为每个条目异步调用 getAmount => 函数 return 的最高数字

Lets say the getAmount(entry) function takes 1 second to finish then i have to wait around entries.length seconds. I'm trying to find a way to execute this in 1 second

如果您有五个调用需要一秒钟,您将无法执行,并且 return 一秒钟内从函数中获取一个值。

Is there a way that the function only returns if all processes inside the for are finished?

是的。然而,这是可能的。

如果你map over your array to produce an array of promises that you can await with Promise.all, you can then use Math.max从那个数组中得到最大的数字。

// Generate a random number
function rnd() {
  return Math.floor(Math.random() * (100 - 0) + 0);
}

// Mock API call which returns the number passed into
// multiplied by an erratic method of
// creating a new random number
function getAmount(el) {
  return new Promise(res => {
    setTimeout(() => res((el - rnd()) + rnd()), 500);
  });
}

// Create an array of promises, await them to resolve
// and then return the highest number
async function getHighest(entries) {
  const promises = entries.map(el => getAmount(el));
  const data = await Promise.all(promises);
  console.log(data);
  return Math.max(...data);
}

// Await the promise that `getData` returns
// and log the result
async function main(entries) {
  console.log(await getHighest(entries));
}

const entries = [1, 2, 3, 4, 5];

main(entries);

有一些东西需要等待:

  1. 在父函数中放置异步
  2. 在检查函数调用中加入 await

例如:

export const test = async (
...
): Promise<number> => {
  //...
  await check();
};

可能还有一些方法可以并行进行这些异步调用运行。