Return of an AJAX is not returning value in Function

Asked

Viewed 23 times

-1

I have a function that executes an AJAX, the AJAX response I return in the 'Return', but when I give a console.log the function returns I get no data. Below is the code.

function getListEmployee() {
var ajax = new XMLHttpRequest();

ajax.open("GET", 'http://localhost/erp/api/v1/employee.php');

ajax.responseType = "json";

ajax.send();
ajax.addEventListener("readystatechange" , function () {
    if (ajax.readyState === 4 && ajax.status === 200){
        var response = ajax.response;
        return response;
    }
})
}

const data = getListEmployee()

1 answer

0

The class XMLHttpRequest has an asynchronous behavior, if you put some console.log, will see that they are displayed in a different order, this helps to understand what the flow is like.

Usually when we consume an API in Javascript, we use Promises (async/await).

See your example, returning a Promise and being consumed with then and also with await:

function getListEmployee() {
  return new Promise( (resolve, reject) => {
    const ajax = new XMLHttpRequest();

    ajax.open("GET", "https://putsreq.com/YYHUDSjLxodiUUhdnP0K");

    ajax.onload = function() {
      if (this.status >= 200 && this.status < 300) {
        resolve(ajax.response);
      } else {
        reject(ajax.statusText);
      }
    };

    ajax.onerror = function() {
      reject(ajax.statusText);
    };

    ajax.send();
  });
}

//Com await
(async () => {
  const data = await getListEmployee();
  console.log("Com async", data);
})();

//Resolvendo a promise
getListEmployee()
  .then(response => {
    console.log("Com then", response);
  })
  .catch(err => {
    console.error(err);
  });

See that now, the function getListEmployee returns a Promise and when the API is successfully consumed, we resolve the Promise, otherwise we reject the same.

Consumption can be done with await, that there is to be within an asynchronous function (async) or by resolving the Promise with then/catch.


Documentations:

  • Even putting it this way, I can’t access the value directly, because I need to use the result in another function.

  • You may have to refactor part of your code so that the function that consumes getListEmployee becomes an asynchronous function and can then use await.

Browser other questions tagged

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