如何在Axios响应中更改变量值?

时间:2020-07-25 00:41:16

标签: javascript axios

我正在尝试在axios的中更改变量值。这是我的示例:

var pts = [];

  axios.get('http://www.example.com')
    .then(function (response) {
      pts = response.data;
    });

  console.log(pts);

pts变量仅返回空数组。我只想在GET查询中使用它。我该如何更改?

2 个答案:

答案 0 :(得分:0)

该请求是异步的,因此先打印pt,然后调用该函数

您可以做的是使用诺言,并按以下方式提出您的要求:

const func1 = () => {
    return axios.get("http://www.example.com").then(response => {return response})
}

func1().then(data => {
    pts = data;
})

答案 1 :(得分:0)

使用新的优雅方式ArrayList<Location> GenLocations = new ArrayList<Location>(); public void firstEvent(){ for(int i = 0; i < GenLocations.size(); i++) { Location L = GenLocations.get(i); if(event.getClickedBlock().getLocation().equals(L)) { //Non-relevant code... } } } public void secondEvent(){ if(searchInventory(event.getWhoClicked().getInventory(),"Too big name", 8, true)) { /* Here is where I want the correct XYZ coord from GenLocations.get(i). It is hard to tell whether GenLocations.get(i) is the right position without if(event.getClickedBlock().getLocation().equals(L)){} or going through a bunch of if statements comparing the data of arrays with the current event which is pain staking long and possibly inefficient /* } } mymap<-st_read("county.shp")%>% st_transform(crs = 4326) str(mymap) library(leaflet) # map the polygons in shp mymap %>% leaflet() %>% addTiles() %>% addPolygons() ,它更加简洁易读

async