【发布时间】:2021-12-19 22:29:23
【问题描述】:
假设我需要获取数据来创建卡片。使用 Promise 获取这些数据的最快方法是什么?这是我目前的做法:
async function getCards() {
const promises = []
for (let i = 0; i < 10; i++) {
promises.push(getCard(i))
}
const cards = await Promise.allSettled(promises)
setCards(cards)
}
async function getCard(i) {
const property1 = await getProperty1(i)
const property2 = await getProperty2(i)
const property3 = await getProperty3(i)
const card = <div>
<div>Property 1: {property1}</div>
<div>Property 2: {property2}</div>
<div>Property 3: {property3}</div>
</div>
return card
}
出于我的目的,我不需要 Promise.allSettled,因为我不需要等待所有 10 张卡都完成等待(我可能只是创建一个组件),我可以在它们完成时渲染每张卡。但我仍然希望它尽可能快地并行/执行。我还有哪些其他选择?有没有更好的方法来处理我在 getCard 中所做的事情?
【问题讨论】:
-
这里有实际的异步操作吗?
getProperty1()是做什么的?如果不是,则不会有并行性,因为同步代码在单个线程中运行(除非您使用 webWorkers)。如果您有实际的异步操作,请向我们展示实际的异步代码。尝试使用Promise.allSettled()不会带来任何好处,除非这些承诺正在监视实际的异步代码。 -
另外,promise 不会“执行”。 Promise 只是一些其他操作(通常是异步的)使用的通知机制。它是另一个执行的操作,然后在完成时告诉 Promise,然后 Promise 通知其他代码完成。虽然这主要是命名法,但对于全面了解什么是承诺以及如何使用它也很重要。
-
getProperty 从 API 中获取一个值,其中 i 是 ID
-
然后向我们展示该代码
-
这是我写的伪代码。假设 getProperty 调用 fetch 或类似的东西
标签: reactjs async-await promise parallel-processing fetch