DEV Community

Cory Allen
Cory Allen

Posted on

How to handle a Sequelize promise within a for loop?

I am having trouble querying within Express with Sequelize. I am first querying all QuizAttempts by a user, and then I am querying Articles to refrence the article name to match it to the quiz attempt. (Joins are way over my head). My problem is, I am getting "null" returned when I console.log "Article Data".

exports.home = async (req, res) => {

    const quizAttempts = await QuizAttempts.findAll({
        raw: true,
        where: {
            user_id: req.user.id
        }
    }).then(async (data) => {
        for (let i = 0; i < data.length; i++) {
            const queryName = await Articles.findOne({
                raw: true,
                where: {
                    id: data[i].article_id
                }
            }).then((articleData) => {
                console.log(articleData);
            })
        }
    })
}
Enter fullscreen mode Exit fullscreen mode

I've been told to use Promise.all() in this particular case but I am not fully understanding how I would do so while still retaining the value of i. Any help is appreciated!

Top comments (0)