0

I'm trying to loop through an object by doing:

  const db = admin.firestore()
  const devicesRef = db.collection('devices')
  const devices = await devicesRef.get();
  devices.forEach(async (result, idx, array) => {

  });

But I get an error:

Argument of type '(result: any, idx: any, array: any) => Promise' is not assignable to parameter of type '(result: QueryDocumentSnapshot) => void'.

Which I don't really understand. If I get rid of idx, array the script works perfectly, but I want to know when the last loop is being performed, which is why I add idx, array...

Any ideas what the error messages might mean?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Simon
  • 2,498
  • 3
  • 34
  • 77

1 Answers1

1

Assuming devices is an array of objects, I don't think you can assign your function there as the function only expects one argument which will get individual device. Try:

  const db = admin.firestore()
  const devicesRef = db.collection('devices')
  const result = await devicesRef.get();

  // adds all results to devices list
  List<any> devices = [];
  for (QueryDocumentSnapshot device : result.getResult()) {
    devices.add(device);
  }

  devices.forEach((device idx, array) => {
    if (idx === array.length -1) {
       // Do specific task
    }
    // some async function
    async (someOtherFunction) => {
       // do something with individual device
    }
});
dabishan
  • 671
  • 3
  • 10
  • Thank you for answering. In this implementation will `array` actually return an array? As my objective is to know when I'm at the end of the loop using `if (idx === array.length - 1) {` – Simon Jan 30 '19 at 18:00
  • if you need index, you can still do your way, but remove async at forEach and do it later inside the function. I have updated the answer. – dabishan Jan 30 '19 at 18:12
  • I still get the same error :( `Argument of type '(result: any, idx: any, array: any) => void' is not assignable to parameter of type '(result: QueryDocumentSnapshot) => void'.` – Simon Jan 30 '19 at 18:21
  • Looks like, you are getting QueryDocumentSnapshot not a list or array. So, you will have to convert it to a list. See this [answer](https://stackoverflow.com/questions/50035752/how-to-get-list-of-documents-from-a-collection-in-firestore-android) – dabishan Jan 30 '19 at 18:28
  • Thank you. I actually realized I can do `devices.size` and just keep a counter in the loop :) – Simon Jan 30 '19 at 18:37
  • You can do that too! I still edited my answer for when you need a list out. – dabishan Jan 30 '19 at 18:40