我正在撰寫一個修改firebase條目中標題的端點;然后收集與 firebase 條目相關的所有 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);
})
uj5u.com熱心網友回復:
請重點關注部分
.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
uj5u.com熱心網友回復:
與其使用then承諾TsenseClient,不如回傳承諾,它會then像下面這樣:
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);
})
uj5u.com熱心網友回復:
考慮使用異步等待您可以在 mdn => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function上找到異步函式的檔案
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.
代碼片段示例 img
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478673.html
標籤:javascript
