0

How do I call a method after a ajax fetch has been done?

This is my code so far, but the callback method wont find this.display.

class fourViews {
  static display(data){
  // Some stuff being displayed...
  }
  loadPage(){
   let url = "www.example.com";
   fetch(url).then(function(data) {
     this.display(data);
   }).catch(function(error) {
      // If error.          
   });
  } 
}
Olof84
  • 919
  • 4
  • 14
  • 29

1 Answers1

1

Your method display is static so you should not expect it to be defined on this (which would not be your object anyway). Instead use the class name:

fetch(url).then(function(data) {
    fourViews.display(data);
})

class fourViews {
  static display(data){
    console.log('display called:\n', data.body);
  }
  loadPage(){
    let url = "https://jsonplaceholder.typicode.com/posts/1";
    fetch(url).then(function(response) {
        // Note that the response object has methods to return promises to data,
        // like json():
        response.json().then(function (data) {
            fourViews.display(data); // static methods are not called on `this`
        })
    }).catch(function(error) {
      // If error.          
    });
  } 
}

new fourViews().loadPage();
trincot
  • 317,000
  • 35
  • 244
  • 286
  • You where right about the static part. But still it can't find it. Someone else though wrote some minutes ago suggesting: .then( data => { this.display(data); } ). That code does work though. – Olof84 Nov 03 '17 at 14:30
  • I added a working snippet with a test URL. You should not remove `static`: that seemed OK. Of course, if you *do* remove it, you can make it work with `this`, but why throw away the `static` when it really is a method that needs no link with an instance? – trincot Nov 03 '17 at 14:44