1

I have created a function where i have passed an object as an argument and there are multiple objects which is passed on one by one and the output is an object but it comes as an individual object which is fine because I have written the code in that way now i wanted to store the objects into an array so it becomes an array of objects.and store for all objects here is the tried code which gives single object example

const {db} = require('./constant')
const momentTz = require("moment-timezone");
const { getAuth } = require("./constant");
const officeStatus = async officeActivity => {
  let output = {};
  const maileventQuerySnapshot = await db
    .collection("MailEvents")
    .where("office", "==", officeActivity.office)
    .where("event", "==", "delivered")
    .limit(1).get();
  output["office"] = officeActivity.office;
  output["First Contact"] = officeActivity.attachment["First Contact"].value;
  output["Second Contact"] = officeActivity.attachment["Second Contact"].value;
  output["Office Creation Date"] = momentTz
    .tz(officeActivity.timestamp, officeActivity.attachment.Timezone.value)
    .format("DD MMM YYYY");
  output["Reports Sent"] = maileventQuerySnapshot.docs.length ? true:false
  const officeSubcollectionSnapshot = await db
    .collection(`Offices/${officeActivity.officeId}/Addendum`)
    .where("date","==",parseInt( momentTz(new Date()).subtract(1, "days").format("DD")))
    .where('month', '==', parseInt( momentTz(new Date()).subtract(1, 'days').format("MM"))-1)
    .where('year', '==',parseInt( momentTz(new Date()).subtract(1, "days").format("YYYY")))
     .orderBy("user").orderBy('timestamp')
    .get();
    output['Number of unique Checkin Yesterday'] =
    officeSubcollectionSnapshot.docs.length;

  const activitiesRefSnapshot = await db
    .collection("Activities")
    .where("office", "==", officeActivity.office)
    .where("template", "==", "subscription")
    .where("attachment.Template.value", "==", "check-in")
    .get();
  const phoneNumberArray = [];
  activitiesRefSnapshot.forEach(doc => {
    phoneNumberArray.push(doc.data().attachment["Phone Number"].value);
  });
  const userRecord = await Promise.all(phoneNumberArray.map(getAuth));
  output["Number of checkin Subscription Auth"] = userRecord.filter(
    doc => doc !== undefined
  ).length;
  output["Number of Checkin Subscription No Auth"] = userRecord.filter(
    doc => doc === undefined
  ).length;
  return { output};
};
module.exports = { officeStatus };

and the other file where i have queried the office and passed objects as an argument

 const {admin,db} = require('./constant');
const { officeStatus } = require("./officeStatus");
let execute = async () => {
  try {
    let office = await db.collection("Offices").where("status", "==", "PENDING").get();
    office.forEach(doc => {
      officeStatus(doc.data())
        .then(e => {
            console.log(JSON.stringify(e.output));
        })
        .catch(error => {
          console.log(error);
        });
    });
    return;
  } catch (error) {
    console.log(error);
  }
  return;
};
execute();
 admin.apps[0].delete();


I have get output in this way 
{}
{}
{}....
and I wanted the output in this way 
[{},{},{}]

3 Answers 3

1

The promise inside forEach is not correct. It wouldn't give you expected results. You shouldn't use that as it is not supported. You should consider using for..of or Promise.all. In your case I would suggest to use Promise.all as you need result in array.

Promise.all(office.docs.map(doc => {
  return officeStatus(doc.data())
    .then(e => {

      return e.output;
    })
    .catch(error => {
      console.log(error);
    });
}))
.then(res => console.log(res));

Sign up to request clarification or add additional context in comments.

6 Comments

in your it prints the same way as i showed in my example
it will depend where you have your console. If you put it inside the .then of officeStatus, you will have it as single object but if you put the console in .then of promise.all it will print them as array.
i have copied your code and map is not working according to your solution
what is the error you are getting? What is the output of .then(res => console.log(res));
it prints an array but using this way is not solving my problem because i have to convert this into an array of arrays and print them into an excel file so can you suggest me a way where i can define an array and push them so there is no problem of scope
|
0

Try doing that :

// and the other file where i have queried the office and passed objects as an argument

 const {admin,db} = require('./constant');
const { officeStatus } = require("./officeStatus");
let execute = async () => {
  try {
    let office = await db.collection("Offices").where("status", "==", "PENDING").get();
let arr = new Array();
    office.forEach(doc => {
      officeStatus(doc.data())
        .then(e => {
            arr.push(e)
        })
        .catch(error => {
          console.log(error);
        });
    });
console.log(arr)
    return;
  } catch (error) {
    console.log(error);
  }
  return;
};
execute();
 admin.apps[0].delete();

I just created an array where we push e when we did officeStatus. Then, at the end of the code, we log arr ; the declared array.

1 Comment

when i use this it consoles an empty array and when i console inside you know it consoles as the object is pushes
0
 const {admin,db} = require('./constant');
const { officeStatus } = require("./officeStatus");
let execute = async () => {
let office = await db.collection("Offices").where("status", "==", "PENDING").get()
  const arrayofObject = await  Promise.all(office.docs.map(doc => {
      return officeStatus(doc.data())
        .then(e => {
          // console.log(JSON.stringify(e.output));
          return e.output;
        })
        .catch(error => {
          console.log(error);
        });
    }))
console.log(arrayofObject)
  return;
};
execute();
 admin.apps[0].delete();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.