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

122
Visualizações
Detect if function was called with "then"

I'm making my own ajax function like jQuery and this is what I have so far

const ajax = function(options){
    const defaults = {
        type: 'GET',
        url: window.location,
        data: {},
        success: function(){},
        error: function(){}
    },
    opts = {...defaults, ...options};

    const xhr = new XMLHttpRequest();
    xhr.addEventListener("load", function(){
        opts.success.call(this, xhr.response, xhr);
    });
    xhr.addEventListener("error", function(){
        opts.error.call(this, xhr);
    });
    xhr.open(opts.type, opts.url);
    xhr.send();
}

and I can call it like

ajax({
    success: (data) => {
        console.log(data);
    }
});

It works. But I want to add optional promise to it. So I want to be able to call this function exactly like this but also like

ajax().then(data => {
    console.log(data);
}).catch(error => {
    console.log(error);
});

I'm new to promises so I'm not sure how to modify the function such that I can detect whether to resolve/reject or call callbacks. Also am I doing something that is considered bad practice?

const ajax = function(options){
    const defaults = {
        type: 'GET',
        url: window.location,
        data: {},
        success: function(){},
        error: function(){}
    },
    opts = {...defaults, ...options};

    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.addEventListener("load", function(){
            resolve(xhr.response);
        });
        xhr.addEventListener("error", function(){
            reject(xhr);
        });
        xhr.open(opts.type, opts.url);
        xhr.send();
    });
}
about 4 years ago · Juan Pablo Isaza
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