Я не могу вернуть ответ от запроса ax ios - PullRequest
0 голосов
/ 26 марта 2020

Я пытаюсь создать модуль в узле для возврата json из API, используя запрос ax ios. Но когда я пытаюсь вернуть ответ из функции getJson(), мне ничего не возвращается.

const axios = require('axios');
const authentication = require('./authentication');


const url = `https://api.codenation.dev/v1/challenge/dev-ps/generate-data?token=${authentication.token}`;

const getJson = async () => {
  const response = await axios.get(url);
  // Here i can see the json normally
  console.log(response.data)
  return response.data
}

const response = getJson()
// but here nothing is shows to me in console.
console.log(response)

возврат консоли

Ответы [ 2 ]

2 голосов
/ 26 марта 2020

getJson() фактически возвращает обещание экземпляр. Вам просто нужно набрать await, например:

(async () => {
  const response = await getJson()
  console.log(response)
})();
0 голосов
/ 26 марта 2020

это потому, что const response = getJson() выполняет свой код перед запуском getJson, потому что он асинхронный c и ответ не приходит к этому экземпляру при его выполнении.

# This code runs and executes some point in future when response arrives
const getJson = async ()=>{
  const response = await axios.get(url);
  //Here i can see the json normally
  console.log(response.data)
  return response.data
}

# This code runs and executes immediately which doesn't have response yet
const response = getJson()
...