0

I have been trying to use Axios to GET JSON data from a json-server to mimic a database for a project. I am able to print the data inside the .then() portion of the axios block, but I cannot get Axios to return the data to the function so others can use the data from the JSON server request instead of printing it. Also, I'm not using React for this project so I cannot rely on useState's functions. I've looked at so many other solutions and for some reason I just can't get the data out of the promise.

const axios = require("axios")

const query = (id="", table="businesses") => (
    axios
      .get(`http://localhost:3001/${table}/${id}`)
      
)
const name = (id) => {
    let user = query(id.toString())
    return user
        .then(res => res.data)
        .catch(err => console.log(err))
}

console.log(name(1))

When I try to print the function's returned result, I receive:

server % node dbms.js
Promise { <pending> }

And I expect:

server % node dbms.js
data: {
  id: 1,
  name: "Carl's Jr.",
  address: '123 Flower St.',
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Nolan
  • 49
  • 5
  • 2
    The problem is your expectation. `name`, like `query`, returns a promise. As you already know, if you want the data the promise resolves to, you have to use `.then`, whose callback receives it (you could also look into `async`/`await` syntax, but that is syntactic sugar that doesn't change the fundamental behaviour). Recommended reading: https://stackoverflow.com/q/14220321/3001761. – jonrsharpe Apr 24 '23 at 22:06
  • @jonrsharpe How might you recommend I get the data out once I'm in the inside? I now understand the function returns a promise, but I can't think of what I can do to make a modular getName() from the inside of the then() – Nolan Apr 24 '23 at 22:19

1 Answers1

1

Your top-level code has to await the Promise resolution.

Try this:

const axios = require("axios");

const query = (id="", table="businesses") => axios.get(`http://localhost:3001/${table}/${id}`);
      
const name = (id) => {
    let user = query(id.toString());
    return user
        .then(res => res.data)
        .catch(err => console.log(err));
};


name(1).then(data => {
    // do stuff after promise has resolved
    console.log(data);
});

Hope that helps!

Tom Kleingers
  • 261
  • 2
  • 4