Google Cloud Functions-警告避免嵌套承诺答应/禁止嵌套 [英] Google Cloud Functions - warning Avoid nesting promises promise/no-nesting
问题描述
鉴于以下功能,我得到警告:
警告避免嵌套promises promise/no-nesting(第6行)
我应该如何重新构造该功能以解决警告?
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();
});
});
});
}
您有一个嵌套在另一个诺言then()
中的诺言then()
调用.这被认为是较差的样式,并且使您的代码难以阅读.如果您要执行一系列工作,最好将您的工作一个又一个地 地链接起来,而不是在另一个内部中嵌套一个工作.因此,而不是像这样嵌套:
doSomeWork()
.then(results1 => {
return doMoreWork()
.then(results2 => {
return doFinalWork()
})
})
按以下顺序对工作进行排序:
doSomeWork()
.then(results => {
return doMoreWork()
})
.then(results => {
return doFinalWork()
})
搜索该错误消息也会产生此有用的讨论. /p>
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.
这篇关于Google Cloud Functions-警告避免嵌套承诺答应/禁止嵌套的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!