Please advise if the following code is the best way to remove an object from an array while performing async functions:
// 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.