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

243
Visualizações
How to call a specific function before and after every fetch api request and response

I want to call a function during sending a request and after receiving response with every fetch() function using Vanilla JS. I saw that jquery ajax is providing some kind of $.ajaxsetup for doing this but I want to do it with Vanilla JS. Thanks in advance.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

fetch doesn't have a feature like that. You could write a wrapper function though:

const myFetch = async (...args) => {
    do_before();
    const result = await fetch(...args);
    do_after();
    return result;
}

and then call that function instead of accessing fetch directly.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can do it by overriding the fetch function

// First rename original fetch function
window.originalFetch = window.fetch

// Then override fetch function with your new function
window.fetch = async (... args) => {
    console.log("before");
    // call the renamed fetch function
    const result = await window.originalFetch(...args);
    console.log("after");
    return result;
}


// Then you can use it
fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

Explanation:

First, you change the original function name, then you write your own function with the same name "fetch"

Thanks to @Quentin some of the code copied from his answer

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