Possible Unhandled Promise Rejection. Cannot read

2019-09-12 05:28发布

问题:

I am new to functional Javascript and promises. The code bellow works great until I uncomment this.writeDataToRealm(data.data). Then I get this error:

Possible Unhandled Promise Rejection. Cannot read property 'writeDataToRealm' of undefined

How can I send the data out to a function for further processing?

...
 fetch(url, {
  method: 'GET',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    Authorization: "Bearer " + token
  },
  }).then(function(response) {
    if (response.status !== 200) {
      throw Error(response.statusText);
    } else {
        return response.json().then(function(data) {
          console.log(data);
          return data.data;
        })
      }
    }).then(data => {
      this.writeDataToRealm(data.data)
    }, err => {
      console.log('Fetch Error: ', err);
    });

   }

   writeDataToRealm(data) {
    console.log(data[0]);
    realm.write(() => {
      realm.create('Student', {id: data[0].kp_ID, bb_first_name: data[0].kp_ID});
    });
  }

回答1:

The unhandled rejection is because you forgot to return the inner promise from the then callback, which causes an exception not to bubble to your catch handler:

.then(function(response) {
  if (response.status !== 200) {
    console.log('Error Status Code: ' + response.status);
    // you might want to `throw` here
  } else {
    return response.json().then(function(data) {
      console.log(data);
      return data.data;
    })
  }
});

The problem with Cannot read property 'writeDataToRealm' of undefined is caused by this not being the instance you expected - see How to access the correct this / context inside a callback?. The simplest solution would be using an arrow function for the callback.

…
.then(data => {
  this.writeDataToRealm(data)
}, err => {
  console.log('Fetch Error: ', err);
});