0

I' m trying to get all the doctor users with a specific id, but it does not work. Want the code does: 1. idDoctors contain all the ids from doctors from a specific hospital 2. specialities contain all the specialities form a spesific hospital doctors should be an array that retrieves firstname lastname and speciality of a doctor, but it doesn't

route.get('/doctor/:idHospital', authenticate,  async (req,res) => {
try{
    let idDoctors = await specialityService.getDoctorsId(req.params.idHospital);
    let specialities = await specialityService.allForHospital(req.params.idHospital)
    let doctors =  getDoctor(idDoctors, specialities)
    console.log(doctors)
    res.send(doctors)
} catch(err) {
    console.log(err)
    res.sendStatus(500)
}

})

I tried this but i dont know how to return the doctors array in the previous function without..

function getDoctor(idDoctors, specialities) {
var doctors = new Array()
let doctor
    let i = 0;
    idDoctors.forEach(async(element) => {
        return userService.oneById(element.idDoctor).then((doc) => {
            doctor = {idDoctor: doc.id, lastName: doc.lastName, firstName: doc.firstName, speciality: specialities[i].speciality }
            doctors.push(doctor)
            i++;
        }).catch((err) => {
            console.log(err)
        })
    });

}

also tried this, but again Idk how to return the doctors array.. And i know that it return empty because that is executed before the promise. I am new to promises and didn't really find an answer.

function getDoctor(idDoctors, specialities) {
var doctors = new Array()
let doc, doctor
    let i = 0;
    idDoctors.forEach(async(element) => {
        try{
            doc = await userService.oneById(element.idDoctor)
            doctor = {idDoctor: doc.id, lastName: doc.lastName, firstName: doc.firstName, speciality: specialities[i].speciality }
        } catch (err) {
            console.log(err)
        }
        doctors.push(doctor)
        i++;
    });
return doctors

}

1 Answer 1

1

Use Promise.all here:

async function getDoctor(idDoctors, specialities) {
  const promises = [];
  idDoctors.forEach((el) => {
    promises.push(userService.oneById(el.idDoctor))
  });
  const doctors = await Promise.all(promises)
  const result = doctors.map((doc, i) => ({
    idDoctor: doc.id,
    lastName: doc.lastName,
    firstName: doc.firstName,
    speciality: specialities[i].speciality
  }))

  return result;
}

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

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.