I’m trying to print the result using Xios

Asked

Viewed 356 times

1

I’m trying to understand how Xios works, but I’m stuck when it comes to printing the information on the screen. I can view the result through the browser console and a Undefined on top, but I don’t think there’s any way to solve.

Another problem is that instead of the result, the code shows all the content of the function as text. Where I am missing?

function titulo() {
  axios.get('https://jsonplaceholder.typicode.com/posts/1')
    .then(res => {
      console.log(res.data.title);
    });
}

titulo();

function myFunction() {
  document.getElementById("demo").innerHTML = 'Título do post: ' + titulo; //o que inserir aqui para que seja mostrado o title vindo do axios?
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.js"></script>

<p id="demo" onclick="myFunction()">Clicar para mudar o texto.</p>

  • The problem is that the request is done asynchronously, hence the code that displays the text is executed before the request is processed, you would have to perform the command inside the then or use async await

1 answer

1


The problem is that the request is done asynchronously, hence the code that displays the text is executed before the request is processed, you would have to perform the command inside the thenor use async/await:

async function titulo() {
  let result = await axios.get('https://jsonplaceholder.typicode.com/posts/1')
  return result.data.title
}

async function myFunction() {
  let title = await titulo();
  document.getElementById("demo").innerHTML = 'Título do post: ' + title; //o que inserir aqui para que seja mostrado o title vindo do axios?
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.js"></script>

<p id="demo" onclick="myFunction()">Clicar para mudar o texto.</p>

First set the function with keyword async and when picking up the function result, use the await to wait for processing

When an asynchronous function is called, it returns a Promise. When the asynchronous function returns a value, Promise will be solved with the value returned. When the asynchronous function throws an exception or some value, Promise will be rejected with the value launched.

An asynchronous function may contain a await expression, which pauses a Asynchronous function execution and waiting for Promise resolution passed, and then resumes the execution of the asynchronous function and returns the solved value.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/funcoes_assincronasAsynchronous functions

  • Perfect, worked the way I wish! At least I already know where to go in studies. Thank you!

Browser other questions tagged

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