Promise.all()

您所在的位置:网站首页 nodejs14新特性 Promise.all()

Promise.all()

2023-11-30 19:03| 来源: 网络整理| 查看: 265

在 async 函数中,“过度 await”代码非常普遍。例如,给定以下函数:

js

function promptForDishChoice() { return new Promise((resolve, reject) => { const dialog = document.createElement("dialog"); dialog.innerHTML = `

What would you like to eat?

Pizza Pasta Salad Cancel OK `; dialog.addEventListener("close", () => { if (dialog.returnValue === "ok") { resolve(dialog.querySelector("select").value); } else { reject(new Error("User cancelled dialog")); } }); document.body.appendChild(dialog); dialog.showModal(); }); } async function fetchPrices() { const response = await fetch("/prices"); return await response.json(); }

你可能会写一个像下面这样的函数:

js

async function getPrice() { const choice = await promptForDishChoice(); const prices = await fetchPrices(); return prices[choice]; }

然而,请注意,promptForDishChoice 和 fetchPrices 的执行不依赖于彼此的结果。当用户选择他们的菜肴时,可以在后台获取价格,但是在上面的代码中,await 运算符会导致异步函数暂停,直到选择完成,然后再次暂停,直到获取到价格。我们可以使用 Promise.all 并发地运行它们,以便用户在结果给出之前不必等待获取价格:

js

async function getPrice() { const [choice, prices] = await Promise.all([ promptForDishChoice(), fetchPrices(), ]); return prices[choice]; }

Promise.all 在这里是并发方法中的最佳选择,因为错误处理很直观——如果有任何一个 Promise 被拒绝,结果将不再可用,整个 await 表达式会抛出异常。

Promise.all 接受一个 Promise 可迭代对象,因此如果要使用它来并行执行多个异步函数,你需要调用这些异步函数并使用返回的 Promise。直接将函数传递给 Promise.all 是不起作用的,因为它们不是 Promise。

js

async function getPrice() { const [choice, prices] = await Promise.all([ promptForDishChoice, fetchPrices, ]); // `choice` 和 `prices` 仍然是原始的异步函数; // Promise.all() 对非 Promise 不起作用 }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3