ESlint, and the rest of the world, tells me to avoid nesting Promises. However, how can you apply a function to a number of items individually where the previous promise returns an array? For example, I want to run doSomethingWithIt on each element returned by the previous Promise, and also do something with the result of that.
function getSomeThings() {
return new Promise((resolve, reject) => {
resolve(['one', 'two', 'three'])
})
}
function doSomethingWithIt(theThing) {
return new Promise((resolve, reject) => {
console.log(theThing)
resolve("Did a thing")
})
}
getSomeThings().then((things) => {
things.forEach((thing) => {
doSomethingWithIt(thing)
.then((result) => {
console.log(`Result was: ${result}`)
})
})
})
In reality, rather than just printing the return value, that function might return an ID or something useful to log when an operation has completed (e.g. commit to a database).
How can this be achieved without nesting the promises? Would I need to add a step which uses Promise.all to aggregate the results? Or is there a neater way of doing this...