Javascript 在异步函数中从数组中删除对象
请告知以下代码是否是执行异步函数时从数组中删除对象的最佳方法:Javascript 在异步函数中从数组中删除对象,javascript,asynchronous,Javascript,Asynchronous,请告知以下代码是否是执行异步函数时从数组中删除对象的最佳方法: // 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 thr
// 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
我找不到一个很好的方法来实现这一点,所以我使用了一种更同步的方法,使用Promise.allsetted
// 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
})
我使用Promise.allsolited,因为dataPromises会生成对象数组。。改用。我不知道如何使用过滤器。您是否建议我使用确实存在的项创建一个新数组?然后,当所有异步函数完成时,比较两个数组。“仅找到的对象” — 你试过否定你的谓词吗?“关于在同一数组上迭代时对数组进行变异。我不会这样做” — 是的,你正在这样做。这是个坏习惯。“回答前请先阅读一个问题。” — “我从来没有在这里回答过。”塞巴斯蒂安西蒙,对不起。我有点累了。我忘了在我原来的帖子中添加一个中断,所以是的。我正在改变我循环的数组,但我正在打破这个循环。你能给我举一个使用filter和否定谓词的例子吗?谢谢你的帮助,但我还是迷路了。