Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

234
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!