Logan Saruwatari Logan Saruwatari - 1 year ago 92
Javascript Question

ES6: How to use, "this", with fetch?

I have read a decent amount of documentation on ES6 and what has changed with it. I am trying to embrace the new oop syntax with some of the new libraries like fetch. So here's the code I have:

apiCall(url, thisAlias=this){
return response.json();

This is in a base class that has an inherited class and will eventually have many inherited classes. The idea is to have a universal api call using fetch and I can change the domUpdater method per inherited class. I spent a lot of time getting this code to work, aliasing the this keyword so that it could be used within the fetch call. Is there a more elegant way to do this? I can't seem to pass this directly as an argument.

Answer Source

Using arrow functions which have lexical this will help you the most with this particular piece of code

apiCall (url) {
    response => response.json(),
    respObj => this.domUpdater(respObj)
    err => console.error(err.message, err)

Otherwise if you can use the newer async/await, you don't have to worry about this pointing to the wrong thing at all – even without arrow functions.

async apiCall (url) {
  try {
    let response = await fetch(url);
  catch (err) {
    console.error(err.message, err);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download