Reputation: 3
I'm working on my first CLI project and I'm having trouble getting it to execute API requests. I have tried fetch, axios, express, and a couple of npm packages, but I just can't figure out what's wrong. The project will console.log and gather user data from the command line, but will not retrieve API data. I'm using a fake API data url at this point just to be sure it works. Here is the code:
const axios = require('axios');
let apiResponse;
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(function(response) {
apiResponse = response;
console.log('Does this work?')
})
.catch(function (error) {
console.log(error, 'Error');
});
console.log('apiResponse: ', apiResponse);
In the command line I get 'apiResponse: undefined' when I run the file. Again, I've tried using several different libraries so I must be doing something fundamentally wrong. The console.log OUTSIDE of the function prints, but neither console.logs INSIDE are printing. Any help would be greatly appreciated!
Upvotes: 0
Views: 1171
Reputation: 9910
I'm guessing in your console you see
undefined
Does this work?
The .get
method is asynchronous, which means any assignment outside of then
will most likely always be what you initialize it as, in this case nothing, or undefined
.
Here's a high level of how things are actually happening:
1) Create undefined var apiResponse
2) axios.get(...)
3) console.log(apiResponse)
4) #2 completes, assigns to `apiResponse`
5) End execution
Here's one of many resources about Promises.
Move the log statement inside the .then()
block.
const axios = require('axios');
let apiResponse;
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(function(response) {
apiResponse = response;
console.log('Does this work?')
console.log('apiResponse: ', apiResponse);
})
.catch(function (error) {
console.log(error, 'Error');
});
Upvotes: 1