0

I have sample function where I use axios:

function getPosts() {
    var response = null;
    axios.get('https://jsonplaceholder.typicode.com/posts/').then(function(res){
        response = res.data
    });
    return response; // null
}

How can be setted response data to response variable in my case?

Andreas Hunter
  • 4,504
  • 11
  • 65
  • 125

2 Answers2

1

You can take advantage of the fact that axios returns a Promise.

Change your function to this:

function getPosts() {
    return axios.get('https://jsonplaceholder.typicode.com/posts/').then(function(res){
        return res.data;
    });
}

// call getPosts()
getPosts()
   .then(function (data) {
      // now data contains the actual information
   })

Razvan Toader
  • 361
  • 1
  • 3
0
function getPosts() {

  return new Promise(function(resolve, reject){
    axios.get('https://jsonplaceholder.typicode.com/posts/').then(function(res){
      resolve(res);
    }).catch(e) {
      reject({
        error: true,
        message: e
      })
    }
  };
}

Return a promise and resolve it when data will come or reject if it fails

Rahul Rana
  • 455
  • 2
  • 7