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();
      });
    });
  });
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With