aritroper
aritroper

Reputation: 1709

Is there any way to make this node js look more compact?

I am new to node js, and am wondering if there is any way to make this more compact. I am talking specifically about the nested then catch statements. Is there anyway to try to put this into one big then catch, or just return {res:false} once rather than a bunch of repeated time for every then catch?

  const uId = data.uId;
  const id = data.id;
  const updates = {};

  updates["/shared/" + id + "/users/" + uId] = null;
  updates["/users/" + uId + "/shared/" + id] = null;

  return admin.database().ref().update(updates).then(() => {
    let ref = "/shared/" + id
    // Check if any members are left
    return admin.database().ref(ref).once("value").then((snapshot) => {
       var users = snapshot.val().users;
       if (users == null) {
         admin.database().ref(ref).remove().then(() => {
           return {res: true};
         }).catch(() => {
           return {res: false};
         });
       } else {
         return {res: true};
       }
    }).catch(() => {
      return {res: false};
    });
  }).catch(() => {
    return {res: false};
  });

Upvotes: 0

Views: 53

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370879

Return the next Promise in the chain instead of nesting them, then have a single .catch at the end:

const ref = "/shared/" + id
return admin.database().ref().update(updates)
    .then(() => {
        // Check if any members are left
        return Promise.all([ref, admin.database().ref(ref).once("value")]);
    })
    .then(([ref, snapshot]) => {
        var users = snapshot.val().users;
        if (users == null) {
            return admin.database().ref(ref).remove();
        }
    })
    .then(() => ({ res: true }))
    .then(() => ({ res: false }));

The Promise.all is needed to pass the value from one .then to another.

Using async/await would make things cleaner:

const ref = "/shared/" + id
try {
    await admin.database().ref().update(updates);
    const snapshot = await admin.database().ref(ref).once("value");
    const { users } = snapshot.val();
    if (users == null) {
        await admin.database().ref(ref).remove();
    }
    return { res: true };
} catch (e) {
    return { res: false };
}

Upvotes: 4

Related Questions