我是功能性Javascript和承诺的新手 . 代码bellow工作得很好,直到我取消注释this.writeDataToRealm(data.data) . 然后我收到这个错误:
可能未处理的承诺拒绝 . 无法读取未定义的属性'writeDataToRealm'
如何将数据发送到函数以进行进一步处理?
...
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 回答
unhandled rejection
是因为你忘记了then
回调中的内部承诺,这导致异常不会冒泡到你的catch
处理程序:Cannot read property 'writeDataToRealm' of undefined
的问题是由this
不是您预期的实例引起的 - 请参阅How to access the correct this / context inside a callback? . 最简单的解决方案是使用箭头函数进行回调 .