JavaScript,Promise 拒绝
2021-01-25
76
我正在尝试创建这个承诺:
const getTocStatus = new Promise((resolve, reject) => {
const userInfo = Auth.currentUserInfo();
resolve(userInfo.attributes['custom:tocStatus']);
reject(new Error('Couldn\'t connect to Cognito'));
});
然后像这样使用它:
getTocStatus.then((response) => {
if (response === 'pending) { //do sth }
}, error => console.log('Error:', error)
但是我收到了错误:
[TypeError: undefined is not an object (evaluating 'userInfo.attributes['custom:tocStatus']')]
承诺和它调用的编码有什么错误?
3个回答
Lionel 的回答是正确的(我不知道
Auth.currentUserInfo
是什么,但没有必要使用
Promise 构造函数
,因为你已经在处理承诺了:
const getTocStatus = async () => {
try {
const userInfo = await Auth.currentUserInfo()
return userInfo.attributes['custom:tocStatus']
} catch (e) {
new Error("Couldn't connect to Cognito")
}
}
// or with .then syntax
const getTocStatus = () =>
Auth.currentUserInfo()
.then((userInfo) => userInfo.attributes['custom:tocStatus'])
.catch((e) => { Promise.reject(new Error("Couldn't connect to Cognito")) })
Zac Anger
2021-01-25
问题是
Auth.currentUserInfo
给你一个承诺,而不是一个值,所以你需要等待它完成才能返回其内容。Mario Vernari 也说对了,你的错误处理也有问题,但这不是你的代码崩溃的原因。这有望解决这两个问题。
const getTocStatus = new Promise(async (resolve, reject) => {
try {
const userInfo = await Auth.currentUserInfo();
resolve(userInfo.attributes['custom:tocStatus']);
} catch (e) {
reject(new Error('Couldn\'t connect to Cognito'));
}
});
Lionel Foxcroft
2021-01-25
您必须区分何时有错误,何时没有错误:
const getTocStatus = new Promise((resolve, reject) => {
try {
const userInfo = Auth.currentUserInfo();
resolve(userInfo.attributes['custom:tocStatus']);
}
catch (err) {
reject(new Error('Couldn\'t connect to Cognito'));
}
});
...或类似的东西。
Mario Vernari
2021-01-25