I am writing in typescript and I have an object with distinct keys, each mapping to a value. I want to iterate over the keys and do an asynchronous function with their value. I know that you can encase .map (to iterate over arrays) in Promise.all, but how can you do it iterating over a for (let i in object) loop? I'm open to other options that allow all keys to be run concurrently, but waiting on all to complete. Edit: I don't want to use Object.keys because I don't want to iterate over the entire objects keys more than once (Object.keys iterates over the objects keys once, and then I will have to iterate for Promise.all)
Object.entries() can get the keys and values. Collect promises for each key-value pair, and fulfill them with all()
.
function asyncFunctionWithKeysAndValuesOf(object) {
let promises = Object.entries(object).map(keyValue => somePromiseReturningFn(keyValue[0], keyValue[1]))
return Promise.all(promises)
}
If you're sensitive to iterating the object more than once...
let promises = []
for (key in object) {
promises.push(somePromiseReturningFn(key, object[key]))
}
return Promise.all(promises)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With