简体   繁体   中英

Keep an index of fetch asynchronized operation

I have to fetch photos like this:

  for (const imgurl of urls){
        fetch('https:/........url=' + imgurl)
        .then(res => res.blob())
        .then(blob => {
          console.log(blob);
          blobs.push(blob);
        });

I would like to keep the order of the for loop when i insert the photos into the array. Which mean, that i am looking for a way to:

  1. Add an index to the fetch locally , and read it on the callback.
  2. When i get the callback with the index , insert the result blob to the right index in the blobs array. (if i got index 4 before 2, put it in 4, or save and reorganize the array later somehow)

Assuming the array size is unknown and can be 5-9.

use Promise.all:

  const fetches = [];
  for (const imgurl of urls){
    fetches.push(fetch('https:/........url=' + imgurl));
  });
  Promise.all(fetches).then(async results => {
    for (const res of results) {
      const blob = await res.blob();
      console.log(blob);
      blobs.push(blob);
    }
  });

like this, not tested. Promise.all guarantees you get the array of results in valid order after all fetches are completed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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