Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

133
Vistas
Async / Await not working with http request

I try to get content with an async call and grab the response via an async function. What is wrong with this setup? The result of the console log is always undefined?

_json: function (callback) {
        var xobj = new XMLHttpRequest();

        xobj.overrideMimeType("application/json");
        xobj.open('GET', this.options.url, true);

        xobj.onreadystatechange = function () {
            if (xobj.readyState == 4 && xobj.status == "200") {
                callback(xobj.responseText);
            }
        };

        xobj.send(null);
    },

    get: async function () {
        var resp = await this._json(function(response) {
            return JSON.parse(response);
        });

        console.log(resp);
    }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Your _json function is not a Promise. It uses common callback pattern to pass information back asynchronously. You have to wrap it in a Promise first, if you want to use async/await syntax.

new Promise((resolve) => this._json((response) => resolve(JSON.parse(response)))

Then you can await it and receive parsed JSON (as you expect).

about 4 years ago · Juan Pablo Isaza Denunciar

0

In order to use async / await you need to know when to use await in the first place. You cannot just put simply await infront of anything and expect that it somehow awaits something.

So, when should you use await or lets say when does it make sense to use it?

One simple question:

  1. Does your method / function returns an Promise?
    • Yes: You can put await infront of it
    • No: Its useless to use await

We can make that check on your issue:

Does this._json() returns an Promise?

In your case no. That means using await is useless.

What you can do is returning an promise:

  _json: function () {
    return new Promise((res, rej) => {
      var xobj = new XMLHttpRequest()

      xobj.overrideMimeType('application/json')
      xobj.open('GET', this.options.url, true)

      xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status === 200) {
          res(xobj.responseText)
        } else {
          rej('Something went wrong')
        }
      }
      xobj.send(null)
    })
  },

  get: async function () {
    var resp = await this._json()
    console.log(resp)
  },

this._json() returns an Promise now. In this case it makes sense to use await.

Remember: By putting async infront of an function,your function then returns also an promise.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda