0

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!

1 Answer 1

1

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');
  });
Sign up to request clarification or add additional context in comments.

8 Comments

I thought about that, but the log statement that's already inside the .get doesn't print. I don't think it's getting inside of that function for some reason.
I've never used axios, but I just ran your code and it works. requirebin.com/?gist=e00bc8e08eae1dbc8671ea86c4315c5d
That doesn't work for me either. Is it something with my dev environment?
Maybe. Can you put your project on github?
Forked and moved some stuff around: github.com/GeerSwitch/lob-coding-challenge
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.