简体   繁体   中英

How to user Select Query inside forEach in Node.Js?

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);
});

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);
})

});

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!' }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM