使用promises检查用户的数据库。寻找一种方法,即使承诺被拒绝,我也可以构建.then
。我可以用.then
处理被拒绝的承诺吗?基本上结合我现有的.then
和.catch
getUserData(UserId)
.then((data) => {
if (data.Item.UserId == UserId ) {
console.log("Welcome Back");
var checkFirst = "returning";
}
})
.catch((err) => {
console.log(err);
console.log("It's a stranger");
var checkFirst = "firstSession";
});
编辑 - getUserData函数:
function getUserData(UserId) {
const docClient = new AWS.DynamoDB.DocumentClient();
const params = {
TableName: "XXXXXXXXXXX",
Key: {
"UserId": UserId,
}
};
return docClient.get(params).promise();
}
答案 0 :(得分:0)
这似乎有效,欢迎任何其他建议
getUserData(UserId)
.then((data) => {
if (data.Item.UserId == UserId ) {
console.log("Welcome Back");
var checkFirst = "returning";
return checkFirst;
}
})
.catch((err) => {
console.log(err);
console.log("It's a stranger");
var checkFirst = "firstSession";
return checkFirst;
})
.then((checkFirst) => {
console.log(checkFirst)
})
答案 1 :(得分:0)
另一种方法是考虑使用async
/ await
,它在语义上更简单,可以像这样写代码。
try {
const data = await getUserData(userId);
} catch (e) {
console.error(e);
}
// continue
答案 2 :(得分:0)
让我们简化..
第1步:
// wrap to always land inside .then
function handleAlwaysThen(UserId) {
return getUserData(UserId)
.then((data) => {
if (data.Item.UserId == UserId) {
return {success: true, checkFirst: "returning"};
}
return {success: false, checkFirst: "UserId not matched"};
})
.catch((err) => {
return {success: false, checkFirst: "firstSession"};
});
}
第2步:
// now just handle .then
handleAlwaysThen(UserId)
.then((data) => {
// do whatever you want with data.success data.checkFirst
});