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

一个简单的问题:我想将简单的数字添加到一个数组中,稍后我想将其与另一个数组进行比较。但是我无法访问更新数组的内容。


这是我的代码:


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"


}

要继续比较我的更新数组和当前数组的内容,我需要确保我得到了正确的值......


任何人的想法?


大话西游666
浏览 120回答 1
1回答

慕标琳琳

此代码是异步的。我建议你看看异步 javascript 代码是如何工作的。基本上你在做什么是这样的:创建一个空数组发出 Axios 获取请求。当这完成时,转至 2.1,如果失败转至 2.2。2.1 推送到数组2.2 日志错误发出 Axios 获取请求。当这完成时,..3.1 ..3.2 ....显示数组中索引 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])}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript