简体   繁体   English

Promise.all /用于等待并获取它的查询数组

[英]Promise.all/for await and fetch array of queries for it

Can i 我可以吗

array.push(fetch(`something`))

For execution in Promise.all / for await, or 在Promise.all /中等待执行,或者

fetch(`something`)

execute itself before i push it in array and not further in code when i want it? 在我将它推入数组之前执行自己,而不是在我想要它的代码中进一步执行?


More info: 更多信息:

Let assume i need to do many queries with for await (if i want to execute them one after another) or Promise.all (if i want to execute them async together). 假设我需要做很多查询for await(如果我想一个接一个地执行它们)或Promise.all(如果我想一起执行它们async)。

I make an queries array: 我创建一个查询数组:

let queries = []
let allResults = []

Push there promises: 推到那里承诺:

tiersQueries.push(fetch(`something`))

And them execute it like this: 他们这样执行:

for await (const oneResult of queries) {
 allResults.push(oneResult)
}

Or this: 或这个:

let results = await Promise.all(array)
allResults = results

The way promises work, they will immediately start executing when created, but they store their status (resolved or rejected or pending) so that even .then or .catch handlers attached after they are completed will still fire. 该承诺的方式工作,创建时,将立即开始执行,但它们存储他们的状态(解决或拒绝或挂起),使得即使.then.catch处理他们完成仍将火灾后附。 Similarly, Promise.all just waits for all the promises to be resolved, it doesn't care whether they were resolved before you passed them .all . 同样, Promise.all只是等待所有的承诺得到解决,它并不关心它们是否在你通过它们之前得到了解决.all That means you're perfectly fine pushing all the fetches to an array and using Promise.all to attach resolution handlers for processing the results of all of them whenever they complete (even if they all complete before the .all runs). 这意味着将所有提取推送到数组并使用Promise.all附加解析处理程序以便在完成时处理所有提取的结果(即使它们都在.all运行之前完成)也是完美的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM