问题描述
鉴于以下功能,我收到警告:
警告避免嵌套承诺承诺/无嵌套(第 6 行)
我应该如何重新构造函数以修复警告?
function FindNearbyJobs(uid, lat, lng){返回 admin.database().ref(`users/${uid}/nearbyjobs`).remove().then(data => {返回新的承诺((解决,拒绝)=> {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];如果 (cO.val().includes(cP.val())){return admin.database().ref(`users/${uid}/nearbyjobs/${key}`).set({ d: distance });}别的{返回空;}});});geoQueryJobs.on("ready", () => {解决();});});});}
您有一个 promise then()
调用嵌套在另一个 promise 的 then()
中.这被认为是糟糕的风格,并使您的代码难以阅读.如果您有一系列工作要执行,最好将您的工作一个接一个串联起来,而不是一个嵌套另一个.所以,不要像这样嵌套:
doSomeWork().then(results1 => {返回 doMoreWork().then(results2 => {返回 doFinalWork()})})
这样安排工作:
doSomeWork().then(结果 => {返回 doMoreWork()}).then(结果 => {返回 doFinalWork()})
搜索该错误消息也会产生这个有用的讨论.>
Given the following function I get the warning:
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.
这篇关于Google Cloud Functions - 警告避免嵌套承诺承诺/无嵌套的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!