Callback in anonymous function returns Undefined

Asked

Viewed 152 times

-1

I need to create two functions.

One of them where I will make a request in Javascript to pick up a Bearer Token, and the second, I will use the token to call another function.

However, I’m not getting the return of the first function.

The code is that way:

function getAuthToken() {
  const url = "https://jsonplaceholder.typicode.com/posts";
  const params = {
    "login" : "admin",
    "password" : "123456"
  };

  $.ajaxSetup({
     headers:{
        'Accept': "application/json"
     }
  });

  $.post(url, params, function(response, status) {
    if(status == 'success') {
      return response.token
    }
  });
}

console.log(getAuthToken())

Every time I give the console.log to try to catch the result, gives a Undefined value. But if I give one console.log within the function itself, without giving the Return, the return is as follows:

{
   login:"admin",
   password:"123456",
   id:101
}

The difficulty I’m having is getting sponse and return to the main function, and then I can get this token and use it in a second function.

1 answer

2


John,

Ao uses the $.post, you are using an asynchronous function, soon it will go through this chunk of code and will not wait for the return of the API, the callback of the post is executed asynchronously, so when placing a console.log within it you can see the response.

In cases like this you can use async/await, declaring the function that consumes the API as asynchronous and when consuming the API and the function itself, using the await.

See an example below:

//Declaração da função getAuthToken como assíncrona
async function getAuthToken() {
  const url = "https://jsonplaceholder.typicode.com/posts";

  const params = {
    "login" : "admin",
    "password" : "123456"
  };

  $.ajaxSetup({
     headers:{
        "Accept": "application/json"
     }
  });

  //Ao consultar a API, utilizo do await, para esperar o retorno da API
  return await $.post(url, params);
}

//Função anônima assíncrona, pois só posso utilizar do await dentro de uma função assíncrona
(async () => {
  console.log( await getAuthToken() );
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

References:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/funcoes_assincronas https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await


If you look right here at stackoverflow, you’ll see that it has a lot of content on JS async/await: /search?q=async+await+%5Bjavascript%5D

  • You could also declare getAuthToken async, not to use an anonymous function.

Browser other questions tagged

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