Access variable of a Function in another Function

Asked

Viewed 115 times

5

I’m starting in Javascript and I’m having the following difficulty, I need to take a variable and access it in another Function.

I have created a variable without specifying anything making it global, but it did not work here, using the console returns as undefined.

I need to take what returns from "axios.get()" be the .then or .catch and access it in btnElement.onclick = function ().

var inputElement = document.querySelector('input');
var btnElement = document.querySelector('button');
var listElement = document.querySelector('.div lista');


btnElement.onclick = function () {
    var listItemElement = document.createElement('ul');

    pegarRepositorio();

    // QUERO USAR O "RESPONSE" AQUI

};


function pegarRepositorio() {

    var inputValue = inputElement.value;

    axios.get(`https://api.github.com/users/${inputValue}/repos`)
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.warn('Erro 404 - Usuário não encontrado');
        });
};

1 answer

7


You can make your request form asynchronous. When an asynchronous function is called, it returns a Promise.
An asynchronous function is different from a synchronous function because an asynchronous function does not block processing so asynchronous function can contain an expression await, which pauses the execution of the asynchronous function and waits for the resolution of the Promise passed, and then resumes execution by returning the solved value.

In case I tested with the user id value mojombo which was the first value obtained in the consultation https://api.github.com/users :

let inputElement = document.querySelector('input');
let btnElement = document.querySelector('button');


btnElement.onclick = async function() {

  //Pausa a execucão até pegarRepositorio() retornar um valor ou falhar.
  let repositorio = await pegarRepositorio();
  //Verifica se houve erro
  if (repositorio.error == null) {
    //Caso não houver erros
    console.log(repositorio["data"]);
  } else {
    //Caso houver erros
    console.error(repositorio.error);
  }

};


async function pegarRepositorio() {
  let inputValue = inputElement.value;
  let d = {};
  try {
    //Pausa a execução até axios.get() retornar um valor ou falhar
    d = await axios.get(`https://api.github.com/users/${inputValue}/repos`, {
      timeout: 3000
    });
  } catch (err) {
    d.error = err;
  }
  return d;
};
<input type="text" value="mojombo">
<button>Clique</button>

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

  • Good afternoon Augusto, show, worked out here. Just one question, I need to return on the screen, if the user is typed wrong, must be returned error 404... so . then/. catch, how do I keep them?

  • 1

    @Rafaelsimionato I made an edition in the reply and see if it meets your expectations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.