我正在编写一个端点,它修改了一个火基条目中的标题;然后收集与火基条目相关的所有Typesense条目,并对它们进行修复。
我的代码就像我想要的那样工作。但是,我最终在.then()嵌套方面比我想要的更深入了一个层次,从而产生了2个.catch()语句,而不是一个。
它觉得这在形式上是错误的,我很想修复它,但我不知道如何“摆脱”它。
db.collection('posts').doc(post.id)
.update({
caption: post.caption
})
.then((data) => {
// tsense collect all with fireId
let searchParameters = {
q: '*',
filter_by: `fireId:=${post.id}`
}
TsenseClient.collections(Collection).documents().search(searchParameters)
.then((data) => {
console.log(data);
return data
})
.then((tsenses) => {
// tsense update all with fireId
let tsenseUpdates = []
tsenses.hits.forEach((hit) => {
let doc = {
"caption": post.caption
}
tsenseUpdates.push(TsenseClient.collections(Collection).documents(hit.id).search(searchParameters))
})
return Promise.allSettled(tsenseUpdates)
})
.then((tsenseUpdates) => {
response.send('Update done.')
})
.catch((err) => {
console.log(err);
})
})
.catch((err) => {
console.log(err);
})发布于 2022-05-20 09:31:02
请把注意力集中在部分
.then((data) => {
// tsense collect all with fireId
let searchParameters = {
q: '*',
filter_by: `fireId:=${post.id}`
}
TsenseClient.collections(Collection).documents().search(searchParameters)
.then((data) => {
console.log(data);
return data
}) 并将其替换为:
.then((data) => {
// tsense collect all with fireId
let searchParameters = {
q: '*',
filter_by: `fireId:=${post.id}`
}
return TsenseClient.collections(Collection).documents().search(searchParameters)
})
.then((data) => {
console.log(data);
return data
}) 您可以阅读更多关于它的https://medium.com/@justintulk/flattening-nested-promises-in-javascript。
发布于 2022-05-20 09:34:44
您不应该在then承诺上使用TsenseClient,您应该返回该承诺,它将像以下所示的then-able:
db.collection('posts').doc(post.id)
.update({
caption: post.caption
})
.then((data) => {
// tsense collect all with fireId
let searchParameters = {
q: '*',
filter_by: `fireId:=${post.id}`
}
return TsenseClient.collections(Collection).documents().search(searchParameters)
})
.then((data) => {
console.log(data);
return data
})
.then((tsenses) => {
// tsense update all with fireId
let tsenseUpdates = []
tsenses.hits.forEach((hit) => {
let doc = {
"caption": post.caption
}
tsenseUpdates.push(TsenseClient.collections(Collection).documents(hit.id).search(searchParameters))
})
return Promise.allSettled(tsenseUpdates)
})
.then((tsenseUpdates) => {
response.send('Update done.')
})
.catch((err) => {
console.log(err);
})发布于 2022-05-20 09:39:43
考虑使用异步等待,您可以在mdn => 函数上找到异步函数的文档。
async function foo() {
const p1 = new Promise((resolve) => setTimeout(() => resolve('1'), 1000)) const p2 = new Promise((_,reject) => setTimeout(() => reject('2'), 500))
const results = [await p1, await p2] // Do not do this! Use Promise.all or Promise.allSettled instead.}
foo().catch(() => {}) // Attempt to swallow all errors.https://stackoverflow.com/questions/72316592
复制相似问题