0

Can i

array.push(fetch(`something`))

For execution in Promise.all / for await, or

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).

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
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
ZiiMakc
  • 31,187
  • 24
  • 65
  • 105
  • `fetch()` returns a promise and does not wait for anything. – SLaks May 21 '19 at 19:47
  • so data fetching at this point already started? – ZiiMakc May 21 '19 at 19:48
  • 1
    Yeah, it's already started – Evgeniy Malyutin May 21 '19 at 19:51
  • you can store all the api links in an array and then loop on that Array to store the result in another array of all the fetch responses. Then after that, fetch responses further return Promises, so these can be handled by Promise.all(); – Rehan Sattar May 21 '19 at 19:54
  • 1
    I think you just have to wrap something and it will work out. I suggest you to bring up the real code (more than yet, as a working unit, not everything ofc, but relevant part..), so you can show where's exactly your problem. Coders like code. – Silvan Bregy May 21 '19 at 19:58
  • Your first approach is basically `Promise.all` in 3 lines of code, 4 if you count initializing the result array. – Jake Holzinger May 21 '19 at 19:59
  • 1
    @SilvanBregy done: https://stackoverflow.com/questions/56245587/how-to-make-array-of-queries-for-for-await-loop – ZiiMakc May 21 '19 at 20:02

1 Answers1

0

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. 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. 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).

IceMetalPunk
  • 5,476
  • 3
  • 19
  • 26