nodejs / node

Node.js JavaScript runtime ✨🐢🚀✨
https://nodejs.org
Other
108.1k stars 29.86k forks source link

while loop block #13960

Closed RifeWang closed 7 years ago

RifeWang commented 7 years ago

I used a while loop and mongoose in mycode : let's see the care here part .

 let result = []; 
 model.WithdrawModel.find({status:'processing'}, (err, doc) => {
            if (err) {
                console.log(err);
                res.json({ code: -1, msg: 'failed'});
                return;
            } else {

                let count = 0; // care here
                let len = doc.length; 

                doc.map((item) => {
                    model.UserModel.findOne({phone:item.phone},'name IDcard bank bankCard bank_area bank_name', (err, bankInfo) => {
                        if (err) {
                            console.log(err);
                        } else {
                            let obj = {};
                            Object.assign(obj, JSON.parse(JSON.stringify(item)), JSON.parse(JSON.stringify(bankInfo)));
                            obj._id = item._id;
                            result.push(obj);
                            console.log(result);
                        }

                        count++; // care here
                        console.log(count); // care here

                    })
                });

               //care here
                while(count < len) {
                    console.log(count);
                }

                res.json({ code: 0, msg: 'success', result: result});
                return;
            }

I find that in the while loop , the code block and aways log 0 , this means count++ doesn't work , but when i delete the while loop part , count++ is work . Is this the mongoose problem? i don't kown . OR something bug when use the while loop in node.js's event-loop?

evanlucas commented 7 years ago

the doc.map() call is calling asynchronous functions that won't update the count variable until some time in the future. The while loop is executing synchronous, so this is expected.

I'm going to go ahead and close as this is not a bug in core. If you have more questions, please open an issue at https://github.com/nodejs/help/issues. Thanks!

RifeWang commented 7 years ago

@evanlucas I still don't understand , althoungh the while loop is executing synchronous , but when the count++ finished in asynchronous functions , I think it will go continue not block .

evanlucas commented 7 years ago

that while loop will never end because it blocks those asynchronous functions' callbacks from being executed. You would need to wait until all of the callbacks have been executed before calling res.json(). It would probably be easier to use a flow control library like async when doing this though