为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我的数组推送不能以正确的方式工作?

为什么我的数组推送不能以正确的方式工作?

大话西游666 2021-12-02 15:28:09
一个简单的问题:我想将简单的数字添加到一个数组中,稍后我想将其与另一个数组进行比较。但是我无法访问更新数组的内容。这是我的代码:checkForUpdates(curr_dataset) {   var current = curr_dataset;  var update = [];  //put in array  axios.get('http://localhost:3030/disruptions/', {    params: {      DisruptionCategory: 0    }  })  .then(response => {    console.log("push " + response.data.data.length)    update.push(response.data.data.length);  })  .catch((error) => {        console.log(error.data);  });  axios.get('http://localhost:3030/disruptions/', {    params: {      DisruptionCategory: 1    }  })  .then(response => {    console.log("push " + response.data.data.length)    update.push(response.data.data.length);  })  .catch((error) => {        console.log(error.data);  });  axios.get('http://localhost:3030/disruptions/', {    params: {      DisruptionCategory: 2    }  })  .then(response => {    console.log("push " + response.data.data.length)    update.push(response.data.data.length);  })  .catch((error) => {        console.log(error.data);  });  axios.get('http://localhost:3030/disruptions/', {    params: {      DisruptionCategory: 3    }  })  .then(response => {    console.log("push " + response.data.data.length)    update.push(response.data.data.length);  })  .catch((error) => {        console.log(error.data);  });  console.log(update[0]); //HERE I GET "undefined"}要继续比较我的更新数组和当前数组的内容,我需要确保我得到了正确的值......任何人的想法?
查看完整描述

1 回答

?
慕标琳琳

TA贡献1830条经验 获得超9个赞

此代码是异步的。我建议你看看异步 javascript 代码是如何工作的。

基本上你在做什么是这样的:

  1. 创建一个空数组

  2. 发出 Axios 获取请求。当这完成时,转至 2.1,如果失败转至 2.2。

    • 2.1 推送到数组

    • 2.2 日志错误

  3. 发出 Axios 获取请求。当这完成时,..

    • 3.1 ..

    • 3.2 ..

  4. ..

  5. 显示数组中索引 0 处的元素是什么。

你看,调用 2.1/3.1/4.1 只有在请求返回成功时才会被执行。在脚本完成之前,Javascript 不会阻止脚本。因此,直到达到 5.,这些请求都不应该完成或失败。这就是为什么没有东西被推送到数组的原因。

在 SO 上,您会找到许多与此相关的示例、博客条目和问题。

此外,对于这些用例,您应该开始使用 async/await。它只是更干净的代码,更容易调试(在我看来)。也使用 const 而不是 var。

一个例子是:

async checkForUpdates(curr_dataset) {

  const current = curr_dataset

  const update = []

  const promises = [0,1,2,3].map(async i => {

    try {

      r = await axios.get('http://localhost:3030/disruptions/', { 

        params: {

          DisruptionCategory: i

        }

      })

      // execute the rest of the code here, like pushing to the array

    } catch (e) {

      console.log(e.data)

    }

  await Promise.all(promises)

  console.log(update[0])

}


查看完整回答
反对 回复 2021-12-02
  • 1 回答
  • 0 关注
  • 111 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信