0

I want to start using axios to get data from a restful api I have already coded, but I keep on recieving [object Promise] instead of something useful like data.

Here is my code.

import axios from "axios";

const get = url => {
  return axios
    .get(url)
    .then(response => {
      return response.data;
    })
    .catch(error => {
      return error;
    });
};

I console.log the return value of this and get [object Promise]. I need the data my restful api is sending back when I call get in the code below.

const {get, post} = client;

const data = get("localhost:4000/data");

console.log(`Data: ${data}`);

Any help is appreciated.

Joshua Blevins
  • 689
  • 1
  • 10
  • 27
  • 2
    You need to wait for the promise by calling `then()`. Learn the basics of promises; you cannot escape from async. – SLaks Sep 14 '18 at 19:10
  • The *point* of a promise is to use asynchronous actions in a synchronous way. Check out `async await` for a neater way to use promises. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function – CodeDraken Sep 14 '18 at 20:00
  • Here is the thing I am not coding something that returns a promise. I have obtained a promise from the code above. I just need to extract something that resembles data. Your link has no relevance here. – Joshua Blevins Sep 14 '18 at 21:05
  • The point of promises is that [they are returnable objects still acting like asynchronous callbacks](https://stackoverflow.com/a/22562045/1048572), to help dealing with asynchronous tasks. But no, it is still fundamentally impossible to extract a value from the promise, as it fulfills in the future only. – Bergi Sep 14 '18 at 21:56

1 Answers1

-1

Your get() returns another promise. In order get data or log it you need to chain it again get().then(console.log);.

Moritz Schmitz v. Hülst
  • 3,229
  • 4
  • 36
  • 63
  • could get().then(data => return data); work? – Joshua Blevins Sep 14 '18 at 19:20
  • 1
    Yes, but it would again return a promise. As @SLaks said: You cannot escape from async. – Moritz Schmitz v. Hülst Sep 14 '18 at 19:22
  • You literally just said get().then is the answer and then tell me no it is not the answer because I didn't use async. Can you show me a working example of getting the data from an axios get request? – Joshua Blevins Sep 14 '18 at 21:04
  • What you have asked is valid syntax. You cannot return from an async function in an asymc scope. Two options: 1. Make the scope async and use await , e.g. `async () => { const data = await get('url'); console.log(data); };` or 2. Put all the logic for handling `data` into the `then()` block e.g. `get().then(data => { console.log(data); // ALL logic around data goes in here });`. – Moritz Schmitz v. Hülst Sep 14 '18 at 21:24
  • 1
    I understand now. It just seems like it doesn't really get you out of callback hell when the final .then() requires a callback or some form of logic or function. – Joshua Blevins Sep 15 '18 at 18:25