问题描述
非常简单的问题.当我在第6行的jsonPayload上运行console.log时,我看到了预期的输出.当我在最后一行的jsonPayload上再次运行console.log时,它返回一个空的{}.如何在初始请求之外访问有效负载?
Very easy question. When I run console.log on the jsonPayload in line 6, I see the expected output. When I run console.log again on jsonPayload in the last line, it returns an empty {}. How do I access the payload outside of the initial request?
var jsonPayload = {}
axios.get('http://localhost:8080/api/tools')
.then(function (response) {
jsonPayload = response.data[0]
// this returns the expected payload
console.log(jsonPayload)
})
.catch(function (error) {
console.log(error)
})
// this returns empty {}
console.log(jsonPayload)
推荐答案
我不确定您为什么要在axios get调用之外访问jsonPayload
,但我确实知道为什么您收到{}
从外部console.log()
.
I am not sure why you would like to access the jsonPayload
outside of the axios get call, but I do know why you are receiving a log of {}
from the outside console.log()
.
axios.get()
上述方法将返回承诺 .此承诺使您可以保护下一个进程免于接收空数据.
The above method will return a promise. This promise allows you to protect your next process from receiving empty data.
在.then()
方法中,您可以检索从axios.get()
调用发送回给您的数据.但是,只有从API检索数据的过程完成后,这些数据才能到达您.
Inside the .then()
method, you are able to retrieve the data that is sent back to you from the axios.get()
call. However, this data cannot reach you until the process of retrieving data from the API, is complete.
这是您遇到问题的地方. .then()
方法外部的console.log()
在ajax调用完成之前被触发.
This is where you are running into your issue. The console.log()
outside of the .then()
method is triggering before the completion of the ajax call.
您还可以考虑使用ES7 async
和await
.这样,您就可以在不使用.then()
的情况下编写这些axios
调用.
You could also look into using ES7 async
and await
. This allows you to write these axios
calls without the .then()
.
这篇关于如何在axios请求之外访问值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!