Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Cloud Functions - warning Avoid nesting promises promise/no-nesting

Given the following function I get the warning:

warning Avoid nesting promises promise/no-nesting (line 6)

How should I re-estructure the function to fix the warning?

function FindNearbyJobs(uid, lat, lng){
  return admin.database().ref(`users/${uid}/nearbyjobs`).remove().then(data => {
    return new Promise((resolve, reject) => {
      const geoQueryJobs = geoFireJobs.query({center: [lat, lng], radius: 3 });
      geoQueryJobs.on("key_entered", (key, location, distance) => {
        return Promise.all([admin.database().ref(`jobs/${key}/category`).once('value'), admin.database().ref(`users/${uid}/account/c`).once('value')]).then(r => {
          const cP = r[0];
          const cO = r[1];
          if (cO.val().includes(cP.val())){
            return admin.database().ref(`users/${uid}/nearbyjobs/${key}`).set({ d: distance });
          }else{
            return null;
          }
        });
      });
      geoQueryJobs.on("ready", () => {
        resolve();
      });
    });
  });
}
like image 328
Diego P Avatar asked Apr 15 '18 17:04

Diego P


1 Answers

You have a promise then() call nested inside another promise's then(). This is considered to be poor style, and makes your code difficult to read. If you have a sequence of work to perform, it's better to chain your work one after another rather than nest one inside another. So, instead of nesting like this:

doSomeWork()
.then(results1 => {
    return doMoreWork()
    .then(results2 => {
        return doFinalWork()
    })
})

Sequence the work like this:

doSomeWork()
.then(results => {
    return doMoreWork()
})
.then(results => {
    return doFinalWork()
})

Searching that error message also yields this helpful discussion.

like image 182
Doug Stevenson Avatar answered Nov 19 '22 08:11

Doug Stevenson