I'm using knexjs (query builder) in a CRUD application. In one part, there's a need to delete from several tables, each table several rows, and reported the deleted rows. The problem is, knex.del() method returns a Promise, and that Promise needs to be resolved inside a for loop. How can I obtain the "report" of the deleted rows in each table in the deleted object by that loop?
I tried methods such as Promise.all, reduce( ) but still facing the same problem (deleted object not resolved).
async function customDelete ( tableList) {
//tableList is an object, where keys = tables, and values correspond to row ids to delete in each table
const deleted = { };
for (const table of tableList) {
if (table in aConditionCheckList) {
console.log("table:", table, "-- ids to delete: ", tableList[table]);
deleted[table] = knex(table).whereIn('id', tableList[table]).del()
.returning('id').
.then( result => {
deleted[table] = result;
notDeleted = tableList[table].filter(x => !result.includes(x));
console.log("***deleted | notDeleted:", result, notDeleted);
if(notDeleted.length){
console.warn('deleting', table, 'no such object(s)', notDeleted);
}
return result;
});
}
}
return deleted;
}
and the part that call customDelete () :
if (req.body && req.body.sync && req.body.sync.delete) {
sync.deleted = await customDelete (req.body.sync.delete);
console.log("deleted rows:", sync.deleted)
}
Without await before knex(table).del( ) the returned object is Promise {<pending>},
deleted[table] = knex(table).whereIn('id', tableList[table]).del().returning('id').then(...)
with await, the script hangs forever.
deleted[table] = await knex(table).whereIn('id', tableList[table]).del().returning('id').then(...)
Expected result: an object:
deleted = { "table1": [1, 2, 4, 5, 12], "table2": [2,3,4,6]} //*etc.*
how do I fix this?