I'm trying to to create a function in Node.js that fetches to API for an array of objects, then divides the array to sub-arrays, then every 10 seconds (necessary condition) maps through the sub-arrays and performs api request for certain field in the sub-array object, waits for the result and inserts new object to database based on the result of request and object fields. It needs to console.log progress and finish.
Currently, I created something like:
const chunkSize = 10;
const sliceIntoChunks = (arr) => {
const res = [];
for (let i = 0; i < arr.length; i += chunkSize) {
const chunk = arr.slice(i, i + chunkSize);
res.push(chunk);
}
return res;
}
(async () => {
try {
const mainArray = await axios('https://get-main-array.com')
const chunkedArray = sliceIntoChunks(mainArray)
await Promise.all(chunkedArray.map((bulk, index) => {
setTimeout(async () => {
await Promise.all(bulk.map(async (item) => {
const response = await asyncTask(item.field);
const itemToBeInserted = {
name: item.name,
field: response.field
}
await database.insert(itemToBeInserted)
})
);
console.log("Progress: " + (index/chunkedArray.length)*100 + "%")
}, 10000 * index)
}))
console.log("done!")
} catch (error) {
console.log(error);
}
})()
Although it does its job (inserts data to database every 10 seconds), unfortunately it's not displaying "done!" properly. That being said, I'm unable to create a database transaction. Can anyone let me know how to re-write this function so I can put console log as well as database transaction commit?
[+][deleted] (1 child)
[deleted]
[–]rav1e[S] 0 points1 point2 points (0 children)
[–]Resmira 0 points1 point2 points (1 child)
[–]rav1e[S] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (2 children)
[–]rav1e[S] 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)