0

I need the result of this axios call. I have tried many ways but I can´t get the promise resolved. I am allways getting promise pending with status resolved and [[PromiseValues]] This is the last one I have tried:

function getResult() {
  let promise = new Promise(function(resolve, reject) {
    resolve(axios.get(URL))
  });

  return promise;
};

let theResult = getResult().then(function(result) {
  return result.data
});
  • 5
    `axios.get(URL)` - is a promise already. Do `axios.get(URL).then(result => result.data);` – Roman Mahotskyi Nov 20 '19 at 14:20
  • It returns Promise {} __proto__: Promise [[PromiseStatus]]: "resolved" [[PromiseValue]]: Array(9) I don´t know how to acces the values – LadyCrispy Nov 20 '19 at 14:28
  • @LadyCrispy that's because you are trying to `console.log` it before it's done. – Nicolas Nov 20 '19 at 14:28
  • How can I use theResult instead? Because when I try to use it, it say it's undefined – LadyCrispy Nov 20 '19 at 16:01
  • This is starting to look like a dup of [How do I return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jfriend00 Nov 20 '19 at 16:52

2 Answers2

0

axios.get - a method that returns a Promise.

Either

axios.get(URL).then(result => result.data);

or

function getResult(url) {
  return axios.get(url);
};

let theResult = getResult('<URL goes here>').then(function(result) {
  return result.data
});
Roman Mahotskyi
  • 4,576
  • 5
  • 35
  • 68
  • I think the issue is that the OP is somehow expecting `theResult` to be their value, but it's still a promise (as it should be). – jfriend00 Nov 20 '19 at 16:53
0

You cannot expect return value from promise by doing var data = getResult(url);. data will have promise object which has its status and value(if resolved or rejected).

function getResult() {
    let promise = new Promise(function (resolve, reject) {
        resolve(axios.get("https://api.github.com/users/mralexgray/repos"))
    });

    return promise; 
};

getResult().then((result) => {

    let theResult = result.data;

    /** process result **/


}).catch((err) => {
    console.log(err, "error");
})

You are resolving your promise to another promise axios.get(URL), because of that you are getting pending as a status even after calling resolve. Try to resolve it with any other value(non-promise) you will get resolved status.

I would recommend you to go through article.

Akshay Bande
  • 2,491
  • 2
  • 12
  • 29