Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

node.js - Async loop didn't wait

I am using node-async-loop for asyncronous programming

var array = ['item0', 'item1', 'item2'];
asyncLoop(array, function (item, next)
{
    do.some.action(item, function (err)
    {
        if (err)
        {
            next(err);
            return;
        }
 
        next();
    });
}, function (err)
{
    if (err)
    {
        console.error('Error: ' + err.message);
        return;
    }
 
    console.log('Finished!');
});

Like this I am using three async loops one under one. I want to send the response only after the third inner loop ends. How can I do so?. Here is the link for node-async-loop (https://www.npmjs.com/package/node-async-loop)

here is my code which i writing but whnever i want to response when the last loop completes it say can set header after send to cliend. also in console log i am getting data every time when data coming from query.

const id = req.params.id;
    finalData = [];
    tb_user.findOne({ where: { id: id } }).then((userRiverSys, err) => {
        if (userRiverSys) {
            // console.log(userRiverSys.regionJson)
            asyncLoop(userRiverSys.regionJson, function (item, next) {
                // console.log("item", item);
                tb_riverSystems.findAll(
                    {
                        where: { regionId: item.id }
                    }).then((findriverSys, err) => {
                        if (err) {
                            next(err);
                            return;
                        }
                        // console.log("findriverSys", findriverSys);
                        if (findriverSys) {
                            asyncLoop(findriverSys, function (item1, next1) {
                                if (err) {
                                    next(err);
                                    return;
                                }
                                // console.log("item1", item1.dataValues);
                                tb_facilities.findAll(
                                    {
                                        where: { riverSystemId: item1.dataValues.id }
                                    }).then((findFacilities) => {
                                        if (findFacilities) {
                                            // console.log("findFacilities", findFacilities[0].dataValues.name);
                                            asyncLoop(findFacilities, function (item2, next2) {
                                                if (err) {
                                                    next(err);
                                                    return;
                                                }
                                                tb_userAccess.findAll(
                                                    {
                                                        where: { facilityId: item2.dataValues.id }
                                                    }).then((userAccessFacilities, err) => {
                                                        // console.log("userAccessFacilities", userAccessFacilities[0].dataValues);
                                                        // var i = 0;
                                                        asyncLoop(userAccessFacilities, function (item3, next3) {
                                                            finalData.push({
                                                                UserId: item3.userid,
                                                                facilityId: item3.facilityId,
                                                            })

                                                            next3();
                                                        },
                                                            function (err) {
                                                                if (err) {
                                                                    console.error('Error: ' + err.message);
                                                                    return;
                                                                }
                                                                // i++;
                                                                // console.log('Finished!!!!');
                                                                // if (userAccessFacilities.length === i) {
                                                                //  console.log("finalData", i);
                                                                //  // res.json({"status":"true", "message":"update OrgChallenge"})
                                                                //    }
                                                            })
                                                            return  res.json({"status":"true", "message":"update OrgChallenge"})
                                                        
                                                            // console.log("finalData", finalData);

                                                    })
                                                next2();
                                            }, function (err) {
                                                if (err) {
                                                    console.error('Error: ' + err.message);
                                                    return;
                                                }
                                                console.log('Finished!!!');
                                            });
                                        }
                                    });
                                next1();
                            }, function (err) {
                                if (err) {
                                    console.error('Error: ' + err.message);
                                    return;
                                }
                                console.log('Finished!!');
                            });
                        }
                    });
                next();
            }, function (err) {
                if (err) {
                    console.error('Error: ' + err.message);
                    return;
                }
                console.log('Finished!');
            });

        } else {
            console.log("err3", err)
        }
    })
question from:https://stackoverflow.com/questions/65646363/async-loop-didnt-wait

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you promisify your asynchronous action (so it returns a promise), then you can just use a regular for loop and async/await and there is no need for a 3rd party library to sequence your asynchronous loop. This is modern Javascript:

const { promisify } = require('util');
do.some.actionP = promisify(do.some.action);

async function someFunction() {
    const array = ['item0', 'item1', 'item2'];
    for (let item of array) {
        let result = await do.some.actionP(item);
        // do something with result here
    }
    return someFinalResult;
}

someFunction().then(result => {
   console.log(result);
}).catch(err => {
   console.log(err);
});

FYI, in real code, many (or even most) asynchronous operations now offer promisified versions of their API already so usually you don't even need to do the promisify step any more. For example, pretty much all databases already offer a promise interface that you can just use directly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...