javascript - 在异步函数中从数组中删除对象
问题描述
请告知以下代码是否是在执行异步函数时从数组中删除对象的最佳方法:
// arr1 holds objects that I've already pulled from the remote db in the past
const arr1 = [ { "hi": "there", "bye": "now" }, ... ]
const conn = connectToRemoteDB()
// loop through list of type of things that I want to pull from remote db
for (const x in listOfObjects)
{
// this is async
conn.execute(sql)
.then (result =>
{
let exists = false
// loop on arr1. can be thousands of objects
for (const i in arr1)
if (result.id === arr1[i].id)
{
exists = true
arr1.splice(i, 1)
break
}
}
}
// will this always be accurate so
// I know anything left in arr1 has been removed from the remote DB
解决方案
I couldn't find a great way to do this so I went with a more synchronous approach using Promise.allSettled.
// oldObjects holds objects that I've already pulled from the remote db in the past
const oldObjects = [{ "hi": "there", "bye": "now" }]
const newObjects = []
const conn = connectToRemoteDB()
let dataPromises = []
// loop through list of type of things that I want to pull from remote db
for (const x in listOfObjects)
{
// this is async
dataPromises.push(conn.execute(sql))
}
Promise.allSettled(dataPromises)
.then(results =>
{
results.forEach(({ status, value }) =>
{
if (status === "fulfilled")
{
for (const r in rows)
{
const queryRow = rows[r]
// loop on oldObjects. can be thousands of objects
for (const i in oldObjects)
if (queryRow.id === oldObjects[i].id)
{
newObjects.push(queryRow.id)
break
}
}
}
})
// compare oldObjects and newObjects to find which objects are no longer in the DB
})
I used Promise.allSettled because the dataPromises results in Arrays of Arrays of Objects.
推荐阅读
- javascript - Javascript 也改变了 const 变量
- java - Android WebView 加载失败 (net::ERR_CLEARTEXT_NOT_PERMITTED)
- c# - 通过逐个编辑单元格在数据网格的底部添加新行
- node.js - 如何更改 MongoDB/Mongoose 文档的位置?
- javascript - 快递中的 res.write 显示其中的 HTML 元素
- php - 通过一个字段选择唯一记录
- amazon-web-services - 使用 terraform 导入我的云 AWS 帐户的当前状态
- database - EAV 建模数据库模式来存储设置,这是正确的方法吗?
- php - 如何在php中将数组的索引值设置为0?
- python - 如何清理字符串以使其仅包含可打印的 ASCII 字符?