0

I am trying to push the fetched data in an array using foreach but it only returns the first data in the loop. Here is my code.

exports.getAllTrial = async function (req, res, next) {

try {
    
    new Promise( async (resolve, reject) => {
        var reservations = [];
        await Schedule.getSchedule()
        .then(data => {
            data.forEach(async (element) => { 
                await saveReserve.getAllTrial({where: {scheduleID: element.id, date: "8/18/2020"}})
                .then(trial => {
                    trial.forEach(response => { 
                        reservations.push(response.scheduleID)
                    })
                }) 
                console.log(reservations);
                resolve(reservations);
            })
        });
    })

    .then(value=>{
        res.status(200).json(value);
    })
    .catch(err => {
        console.log(err);
    });

} catch (e) {
    return res.status(400).json({ status: 400, message: e.message });
}

}

My expected output should be: [ 9, 10, 10 ] But it only returns [9].

1 Answer 1

2

Async code in a foreach loop is a bad idea, as it won't be executed one after the other. I suggest reading a bit more async/await and the concept of promise, as you are mixing things here (such as mixing await and .then). Also worth looking into Promise.all which will resolve a list of promises and array.map.

While I have no idea of what some variables such as saveReserve are supposed to be or do, your code might be simplified into:

exports.getAllTrial = async (req, res, next) => {
  try {
    const data = await Schedule.getSchedule()

    const reservations = await Promise.all(
      data.map(element => {
        return saveReserve.getAllTrial({ where: { scheduleID: element.id, date: '8/18/2020' } })
      })
    )

    return res.status(200).json(reservations)
  } catch (e) {
    return res.status(400).json({ status: 400, message: e.message })
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much. It worked. Yes i'll learn more about it. :)
How can I push an array inside the data.map because I have to get the data from the getSchedule and push with the fetched data from getAllTrial
Th reservations variable will contain the results of all getAll calls, and data contains the result of getSchedule. If data is an array, then you can just use .concat to have a final array with the content of both. It just sound weird to have different type of data in the same array ?

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.