[英]undefined is not an object (evaluating Promise .then)
Im getting this error while developing react native mobile application. 我在开发本机移动应用程序时收到此错误。
fetchDB
function will return a promise fetchDB
函数将返回一个承诺
fetchDB(key) {
try {
AsyncStorage.getItem(key, result => {
return result;
});
} catch (error) {
console.log(error);
}
}
}
fetching value from returned promise by using .then()
通过使用
.then()
从返回的承诺中获取价值
getUserName = () => {
var user = Storage.fetchDB("username");
user.then(res => {
alert(res);
});
};
its rendering the red screen with error 其呈现红色屏幕并显示错误
undefined is not an object
未定义不是对象
1) You need to return the promise function explicitly. 1)您需要显式返回promise函数。 Fail situation could be handled within catch callback:
失败情况可以在catch回调中处理:
fetchDB(key) {
return AsyncStorage.getItem(key).catch(error => console.log(error));
}
fetchDB("username").then(res => alert(res));
2) Point (1) works only if AsyncStorage.getItem
really returns promise. 2)只有当
AsyncStorage.getItem
确实返回promise时,点(1)才AsyncStorage.getItem
。 If it's not true, then you need to update AsyncStorage.getItem
method to be promise-based. 如果不正确,则需要将
AsyncStorage.getItem
方法更新为基于AsyncStorage.getItem
。 If you have not access to that method or don't want to touch it, the issue could be done also via updating fetchDB
function in a way like: 如果您无法访问该方法或不想触摸它,也可以通过以下方式更新
fetchDB
函数来解决此问题:
fetchDB(key) {
return new Promise((resolve, reject) => {
try {
AsyncStorage.getItem(key, resolve);
}
catch (error) {
reject(error);
}
})
}
fetchDB("username")
.then(res => alert(res))
.catch(error => console.log(error));
3) I would even say that you don't need try-catch due to es6 Promises nature: 3)我什至会说由于es6 Promises本质,您不需要try-catch:
fetchDB(key) {
return new Promise((resolve, reject) =>
AsyncStorage.getItem(key, resolve)
)
}
fetchDB("username")
.then(res => alert(res))
.catch(error => console.log(error));
That last .catch
handles any errors thrown from fetchDB
Promise. 最后一个
.catch
处理从fetchDB
Promise引发的任何错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.