I have some code that JSON.stringify's an array of objects like so:
const postsCommentsReadyForDB = postsComments.map(postComments => ({
id: getPostId(postComments),
comments: JSON.stringify(getComments(postComments)),
}))
However on very large amounts of data (e.g. an array of 6000+ objects), it can take up to 3+ seconds for this to complete because of all the JSON.stringify processing.
I'm not so worried about the time it takes to do this, but I would like to avoid blocking the event loop or any I/O, so I thought I could perhaps use setImmediate to solve this.
Here is my approach to doing this with setImmediate:
const postsCommentsReadyForDB = []
postsComments.forEach(postComments => {
setImmediate(_ => {
postsCommentsReadyForDB.push({
id: getPostId(postComments),
comments: JSON.stringify(getComments(postComments)),
})
})
})
However when I run this it doesn't seem to work and postsCommentsReadyForDB is empty.
Is it possible to use setImmediate in this scenario?