Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

loops - How to do something after multiple aysnc requests in Javascript

I have multiple async request running inside 2 loops. I want to reload the page when All the requests inside BOTH loops are done.

I'm a bit confused about this.

If I had one request I would just call window.location.reload in a then block.

If I had two requests I would make the other request in first then block and call window.location.reload inside the second request then block

How should I do this?

seImages.forEach((seImage) => {
  const se_image = {
    image: seImage.image,
    alt_text: seImage.alt_text,
    landing_page: newLp.id,
    csrfmiddlewaretoken: getCookie('csrftoken'),
  };

  const newSeImage = urlEncodedFormData(se_image);

  postFormData(
    ui.urls.createSeImage(),
    newSeImage
  ).then((resp) => console.log(resp));
});

vpPoints.forEach((vpPoint) => {
  const vp_point = {
    point: vpPoint.point,
    description: vpPoint.description,
    landing_page: newLp.id,
    csrfmiddlewaretoken: getCookie('csrftoken'),
  };

  const newVpPoint = urlEncodedFormData(vp_point);
  postFormData(
    ui.urls.createVpPoint(),
    newVpPoint
  ).then((resp) => console.log('VpPoint: ', resp));
});
question from:https://stackoverflow.com/questions/65884549/how-to-do-something-after-multiple-aysnc-requests-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You create an array like const promises = []; and push all the promises promises.push(fetch(...));. After all functions are started and all promises are stored you can simply wait for await Promise.all(promises);

const promises = [];

seImages.forEach((seImage) => {
  const se_image = {
    image: seImage.image,
    alt_text: seImage.alt_text,
    landing_page: newLp.id,
    csrfmiddlewaretoken: getCookie('csrftoken'),
  };

  const newSeImage = urlEncodedFormData(se_image);

  promises.push(postFormData(
    ui.urls.createSeImage(),
    newSeImage
  ).then((resp) => console.log(resp)));
});

vpPoints.forEach((vpPoint) => {
  const vp_point = {
    point: vpPoint.point,
    description: vpPoint.description,
    landing_page: newLp.id,
    csrfmiddlewaretoken: getCookie('csrftoken'),
  };

  const newVpPoint = urlEncodedFormData(vp_point);
  promises.push(postFormData(
    ui.urls.createVpPoint(),
    newVpPoint
  ).then((resp) => console.log('VpPoint: ', resp)));
});

(async function () {
    await Promise.all(promises);
    // window.location.reload
})();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...