This question is already asked, but that not solve my issue.

In my Node.Js project i want to user SELECT Query inside forEach but that not working properly.

I refer some blog they say use async and await i tried but that also not working properly.

This is my code:

db.sequelize.query(query, { type: sequelize.QueryTypes.SELECT} ).then(async dataList=>{
    let cubbersIdList = [];
    // dataList = [{"cubbersId": 27},{"cubbersId": 28},{"cubbersId": 29}]
    await dataList.forEach((value, key)=>{
        CubbersShopsData.findAndCountAll({where:{cubbersId:value.cubbersId}}).then(datas=>{
            cubbersIdList.push(datas);
            console.log("---data---");
        }).catch(error=>{
            logger.error(error);
            res.status(200).send({status: 'error', resCode:403, msg:'Internal Server Error...!', data:error});
        });
    });
    console.log("---data---");
    res.send(cubbersIdList); // get result here
    console.log(cubbersIdList);
});

2 Answers

1
Kunal Mukherjee On Best Solutions

Try to refactor your code like this to use async-await properly.

Call the asynchronous code in the for...of loop and await the promise and resolve the response and push it into your array later.

db.sequelize.query(query, { type: sequelize.QueryTypes.SELECT})
.then(async dataList => {
    let cubbersIdList = [];

    for (const data of dataList) {
        const count = await CubbersShopsData.findAndCountAll({where: { cubbersId: data.cubbersId }});
        cubbersIdList.push(count);
    }

    return res.status(200).json(cubbersIdList); 
})
.catch(err => res.status(500).json({ message: 'Some error occured!' }));
1
rajpoot rehan On

try this install npm

npm install async-foreach --save

add in your file

var forEach = require('async-foreach').forEach;

use forEach like this

db.sequelize.query(query, { type: sequelize.QueryTypes.SELECT} ).then(async dataList=>{
let cubbersIdList = [];
// dataList = [{"cubbersId": 27},{"cubbersId": 28},{"cubbersId": 29}]
forEach(dataList,function(value, key){
    var done = this.async();
    CubbersShopsData.findAndCountAll({where:{cubbersId:value.cubbersId}}).then(datas=>{
        cubbersIdList.push(datas);
        done();
    }).catch(error=>{
        done();
        logger.error(error);
        res.status(200).send({status: 'error', resCode:403, msg:'Internal Server Error...!', data:error});
    });
},function(err){
    res.send(cubbersIdList); // get result here
    console.log(cubbersIdList);
})

});