0

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){
    fetch(url).then(function(response){
    return response.json();
    })
    .then(function(respObj){
        thisAlias.domUpdater(respObj);
    });
}

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

4

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

apiCall (url) {
  fetch(url).then(
    response => response.json()
  ).then(
    respObj => this.domUpdater(respObj)
  ).catch(
    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);
    this.domUpdater(response.json());
  }
  catch (err) {
    console.error(err.message, err);
  }
}
Mulan
  • 129,518
  • 31
  • 228
  • 259
  • Thanks for the quick response. I have seen this arrow notation used but didn't understand why. Can you explain what it is doing or point me in the right direction? Again, thanks, it is hard to find information on ES6 for me. – Logan Saruwatari Oct 26 '16 at 05:22
  • 1
    @LoganSaruwatari Since arrow functions don't bind their own `this` (thus lexical scope), `this` in `then` will refer to the enclosing context or the class. Since regular functions, by default, have their `this` refer to window, doing `this.domUpdater` will do `window.domUpdater` (not correct). You may also bind `this` but arrow functions are generally considered better – Andrew Li Oct 26 '16 at 05:23
  • Wow! you blew my mind with the first block of code, the second block takes it to a whole new level. I need you to be my ES6 mentor. All the good programmers I know don't dabble in js. – Logan Saruwatari Oct 26 '16 at 05:31
  • 1
    The async/await is a proposal (not part of ES6 or "ES2015") but it can be transpiled using babel. I'm happy to help you with any other questions you have. – Mulan Oct 26 '16 at 05:35
  • I haven't tried it yet. The first block of code seems to need the comma after response.json() removed. I was going to ask why it was there but I think it may just be a typo. Can't edit per some permissions issue – Logan Saruwatari Oct 26 '16 at 05:44
  • @LoganSaruwatari sorry about that. it was indeed a typo – Mulan Oct 26 '16 at 07:05