Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Promise.all iterate over object keys

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)

like image 597
Vikram Khemlani Avatar asked Sep 16 '25 00:09

Vikram Khemlani


1 Answers

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)
like image 58
danh Avatar answered Sep 18 '25 18:09

danh