如何等到 Javascript forEach 循环完成后再进行下一个 sep [英] How to wait until Javascript forEach loop is finished before proceeding to next sep

查看:17
本文介绍了如何等到 Javascript forEach 循环完成后再进行下一个 sep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要等待由 forEach 循环调用的函数中的所有 axios 调用运行,然后再调用另一个函数来重新加载应由 axios 调用更新的数据.

I need to wait for all of the axios calls in a function called by a forEach loop to run before I call another function to reload data that should be updated by the axios calls.

function1() {
    let arr = [1, 2, 3, 4, 5];
    arr.forEach((num) => {
        function2(num);
    });
    //Wait until each call in the forEach loop above
    //is done before running the function3() function.
    function3();
}

function2(number) {
    axios.post('/internal-url/action/' + number)
        .then((response) => {
            return response;
        });
}

function3() {
    console.log('reloading data...');
    /* DB call to reload data */
    console.log('data is reloaded');
}

这里的问题是数据在 axios 调用完成之前重新加载.我知道 axios 调用有效,因为我可以看到它们在数据库中更新,但我需要 function1() 等待 function2() 中的所有 axios 调用在 function3() 中运行重新加载之前完成.

The problem here is that the data reloads before the axios calls are complete. I know the axios calls worked because I can see they updated in the database, but I need for function1() to wait for all of the axios calls in function2() to finish before running the reload in function3().

我尝试同时创建 function1()function2() async/await 函数,然后分别创建,但这没有用.我将如何具体执行此操作?

I've tried to make function1() and function2() async/await functions, both at the same time and then individually, but that did not work. How would I go about doing this specifically?

推荐答案

创建一个 promise 数组,然后使用 Promise.all 使用 async/await.

Create an array of promises then use Promise.all to await their resolution/rejection using async/await.

// async/await - create an array of promises
// from function2, then await until Promise.all has
// fully resolved/rejected
async function1() {
  let arr = [1, 2, 3, 4, 5];
  const promises = arr.map((num) => function2(num));
  await Promise.all(promises);
  function3();
}

function2(number) {
  return axios.post('/internal-url/action/' + number);
}

function3() {
  console.log('reloading data...');
  /* DB call to reload data */
  console.log('data is reloaded');
}

这篇关于如何等到 Javascript forEach 循环完成后再进行下一个 sep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆