0
const axios = require('axios');
let api = []
axios.post('http://127.0.0.1:8000/make_json/', {
  api:"{'Link': 'media/pdf/details/all-india-govt-jobs/other-all-india-govt-jobs/1190896199.pdf', 'Title': 'Corrigendum'},{'Link': 'media/pdf/details/all-india-govt-jobs/other-all-india-govt-jobs/3916152215.pdf', 'Title': 'Notification '},{'Link': 'http://www.nia.nic.in/', 'Title': ' Official Website'}"
})
.then(response => {
  api = response.data
})

console.log(api)

here i am assigning response to a variable api which is defined on the top. but when i am trying to console.log() it is coming blank arrray..

please have a look into my code..

  • 3
    Possible duplicate 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) – Orelsanpls Oct 30 '18 at 16:01
  • I am not able to figureout same. could you please write it ?? – Soubhagya Pradhan Oct 30 '18 at 16:08

1 Answers1

0

The console.log() statement returns a blank array because it is being executed before the response from your POST request is returned. This is due to the fact that axios executes requests asynchronously.

To access the data returned from the network request without writing other functions, you need to have your code in the then block like so:

const axios = require('axios');  
let api = []  
axios.post('http://127.0.0.1:8000/make_json/', {
  api:"{'Link': 'media/pdf/details/all-india-govt-jobs/other-all-india-govt-jobs/1190896199.pdf', 'Title': 'Corrigendum'},{'Link': 'media/pdf/details/all-india-govt-jobs/other-all-india-govt-jobs/3916152215.pdf', 'Title': 'Notification '},{'Link': 'http://www.nia.nic.in/', 'Title': ' Official Website'}"
})  
.then(response => {  
  api = response.data  
  console.log(api)
  // other code using `api`...
})

Another option, if you're using at least version 7.6 of Node, is to wrap your code in an async function and await the result:

const axios = require('axios');

async function myCode() {
  const response = await axios.post('http://127.0.0.1:8000/make_json/', {
    api:"{'Link': 'media/pdf/details/all-india-govt-jobs/other-all-india-govt-jobs/1190896199.pdf', 'Title': 'Corrigendum'},{'Link': 'media/pdf/details/all-india-govt-jobs/other-all-india-govt-jobs/3916152215.pdf', 'Title': 'Notification '},{'Link': 'http://www.nia.nic.in/', 'Title': ' Official Website'}"
  })

  let api = response.data
  console.log(api)
  // other code using `api`...
}

myCode() // note that `myCode` will run asynchronously
dpopp07
  • 561
  • 5
  • 10
  • I don't think that it's possible without somehow forcing `axios` to run synchronously. In my second example, you would be able to put all of your code into the `myCode` function and write your program in a synchronous style - it just requires calling that function. What is your specific use case that you need the console statement outside of the function? – dpopp07 Oct 30 '18 at 21:21