Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda