0

why this fuction do not return anything for me. I think I have problem with axios.get.then(). So can you help to make it return message in then(reponse => ...) The main question here is how can i save what function testConnection() return into a variable message to use it many time.

var axios = require('axios');

function testConnection() {

  axios.get(`https://api.themoviedb.org/3/discover/movie`, {
  params: {
    api_key: '72f444fa3d547f8ab38bcc6d9b00ffd6',
    sort_by: 'popularity.desc',
    include_adult: false,
    include_video: false,
    with_genres: 28,
    with_original_language: 'en',
  },
  }).then(response => {
      if (response.length === 0) {
        return "NOT OK";
      }  
        return "OK";
  })
}

var message = testConnection();
console.log(message);

Here is result when I run my code. enter image description here

  • Best to just `return axios.get(...)` and then use `testConnection().then(function(result) { ... });`. More explanation in [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). As it stands now, your `testConnection()` function has NO return value at all. The `return` statements you do have just return from the `.then()` handler not from your host function. – jfriend00 Dec 26 '17 at 01:31
  • I think you shoule unblock my question because my question is how to save the return into a `variable` – Lê Minh Hoàng Dec 26 '17 at 03:42
  • You can't. That is all explained in the dup. The `axios.get()` finishes AFTER the function returns. Can't return an async value from the function. Must use a callback or promise. Study the dup. All explained there. – jfriend00 Dec 26 '17 at 04:07

1 Answers1

0

In writing JS or any other NodeJS code there is rule to wait response from outside resource(EG: database, API).

var axios = require('axios');

function testConnection(callback) {

  axios.get(`https://api.themoviedb.org/3/discover/movie`, {
  params: {
    api_key: '72f444fa3d547f8ab38bcc6d9b00ffd6',
    sort_by: 'popularity.desc',
    include_adult: false,
    include_video: false,
    with_genres: 28,
    with_original_language: 'en',
  },
  }).then(response => {
      callback(response);
  })
}

var message = testConnection(function(response){
   if (response.length === 0) {
        console.log("NOT OK");
      }  
        console.log("OK");
});
Altantur
  • 2,552
  • 1
  • 13
  • 12
  • Better to just return the promise that `axios.get()` already makes than to introduce another callback. – jfriend00 Dec 26 '17 at 01:32
  • I want to use variable `message` many time. How can you fix it. Your code just print out it and I can't use `message` in other place. – Lê Minh Hoàng Dec 26 '17 at 03:36