在屏幕上列出数据

List data on the screen

我想在我的 agents 变量中使用 map 函数,但它不可用,谁能告诉我为什么?

代码如下:

axios(config).then(function (response) {
      agents = response.data;
      console.log('agents', agents);
    });
    // (agents.map) map function is not available here
  }

Javascript 本质上是异步的。因此,无论您在 .then 中做什么修改,该函数都只会反映在同一范围内。

因此,无论您想对从 API 调用接收到的代理值做什么,都应该只在 then 函数内完成。

let agents = [];
axios(config).then(function(response) {
  agents = response.data;
  console.log("agents", agents);
  const mapAgents = agents.map(a => a.someProperty);
  console.log(mapAgents);
  // end of scope for the agent's value, it won't be accessible outside.
});
console.log(agents); // outputs []
// value of agent's won't be accessible here due to async nature. This line will get executed first and then.

异步等待

如果您希望以同步方式执行某些操作。您可以使用 async-await 实现它,它使函数内部同步,同时保持函数的执行异步。

const getAgents = async function() {
  let agents = []
  const res = await axios(config) // thread will wait till the api call is completed
  agents = res.data
  // perform your action here
}

getAgents(); // this will now become asynchronous

您可以了解有关 Javascript 异步性质的更多信息,here