0

Using promises to check a database for the User. Looking for a way I can construct a .then that carries on even if the promise is rejected. Can i handle a rejected promise with .then ? Essentially combine my existing .then and .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";    
});

Edit - getUserData Function:

function getUserData(UserId) {
  const docClient = new AWS.DynamoDB.DocumentClient();
  const params = {
    TableName: "XXXXXXXXXXX",
    Key: {
      "UserId": UserId,
    }
  };

  return docClient.get(params).promise();
}
StMartin
  • 89
  • 7

3 Answers3

0

This seems to work, welcome any other suggestions

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)
})
StMartin
  • 89
  • 7
0

An alternative way would be to consider using async / await, it's semantically simpler to write code like this e.g.

try {
  const data = await getUserData(userId);
} catch (e) {
  console.error(e);
}
// continue
James
  • 80,725
  • 18
  • 167
  • 237
0

Lets simplify it..

Step 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"};
           });
}

Step 2:

// now just handle .then
handleAlwaysThen(UserId)
.then((data) => {
     // do whatever you want with data.success data.checkFirst
});
Zeeshan Hassan Memon
  • 8,105
  • 4
  • 43
  • 57
  • @str I used it like that way so that OP's purpose can be achieved that is getting response in .then no matter promise succeeded (resolved) or failed (rejected). I just only tried to simplify it by adding an additional wrapper. – Zeeshan Hassan Memon Apr 12 '18 at 16:18
  • I understand there are other possible and cool ways to write same code but see the title of this *post* OP just wanted to always land inside .then no matter resolved or rejected. So keeping his requirement and his currently adopted syntax intact I tried to make it simpler for him. Else opinion based there can be solutions and syntax. – Zeeshan Hassan Memon Apr 12 '18 at 16:44