javascript - 等待不等待javascript

标签 javascript async-await

我有以下代码:

var arrayAxios = [];
            
const array = async() => {
  await sleep(3000);
  _.forEach(tasks, task => {
    let res = _.includes("selected", task.value);
    if (res) {
      this.axios
        .get(url, { params: { data1 } })
        .then(response => {
          arrayAxios.push(this.axios.post(url, { dataAAA }));
        });
    }
  });
};
              
var promises = async() => {
  const arrayAxios = await array();
  await Promise.all(arrayAxios)
    .then(response => {
      resetAll_dataAAA();   // <--- my dataAAA in arrayAxios are reset before post in Promise.all!
    })
    .catch(error => {
      console.log(error);
    });
};

promises();

函数“resetAll_data()”在数据发送到 DDBB 之前执行。我找不到问题。

有什么建议吗?

非常感谢!

最佳答案

您正在寻找

async function array() {
  await sleep(3000);
  var arrayAxios = []; // declare the array locally
  _.forEach(tasks, task => {
    let res = _.includes("selected", task.value);
    if (res) {
      arrayAxios.push(this.axios
//    ^^^^^^^^^^^^^^^ push to the array immediately, not asynchronously
        .get(url, { params: { data1 } })
        .then(response => {
          return this.axios.post(url, { dataAAA }));
//        ^^^^^^ chain the promises
        })
      );
    }
  });
  return arrayAxios;
//^^^^^^ give the result to the caller
}

关于javascript - 等待不等待javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55077858/

相关文章:

javascript - d3 有向图编辑器添加

javascript - Nodemailer 使用 POST 表单时返回 404

javascript - 从外部浏览器链接访问/打开应用程序

javascript - 从 chrome 存储中检索日期对象不起作用

javascript - 使用 Google 脚本永久删除我的电子邮件的脚本

javascript - async-await 只与 promises 一起使用吗?

flutter - 为什么这个使用 FakeAsync 的测试只是卡在 "await"上,即使 future 已经完成?

c# - 有没有办法知道是否正在等待任务?

javascript - try/catch 中的异步/等待在等待解决后未显示处理逻辑中的错误

javascript - += 的异步函数