Reputation: 6795
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)
Upvotes: 2
Views: 2726
Reputation: 46
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.
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.
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.
You could also look into using ES7 async
and await
. This allows you to write these axios
calls without the .then()
.
Upvotes: 3
Reputation: 7742
As @d3L answered, you're limited to handle the response within the callback
passed to .then
. However, after ES8 you can use async / await
which is an alternative to using typical Promise handling with callbacks. Is still asynchronous, but looks synchronous:
(async function() {
try {
const response = await axios.get('http://localhost:8080/api/tools');
console.log(response.data[0])
} catch(err) {
console.log(err);
}
})();
Note whether you're running it on node or the browser, the engine might not support it, so you might need to transpile the code using babel.
Upvotes: 0