search

Home  >  Q&A  >  body text

promise mongoose loop through query - Stack Overflow

let result = []; //存放查询结果
model.WithdrawModel.find({status:'processing'}, (err, doc) => {
            if (err) {
                console.log(err);
                res.json({ code: -1, msg: '查询失败'});
                return;
            } else {
                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)));
                            result.push(obj);
                            console.log(result); 
                        }
                    })
                });
                res.json({ code: 0, msg: '查询成功', result: result});
                return;
            }
 });

Looping through the query, the above result directly returns a null value. How can I ensure that all the internal queries in doc.map are completed before taking out the value of result?

天蓬老师天蓬老师2708 days ago1074

reply all(2)I'll reply

  • 仅有的幸福

    仅有的幸福2017-06-29 10:11:23

    Ask and answer your own questions, and receive guidance from others.

    promise.all is implemented as follows:

            let result = []; //存放查询结果
            let doc1 = []; //存放第一次查询的结果
            model.WithdrawModel.find({status:'processing'}).exec().then((doc) => {
                doc1 = doc;
                const promises = doc.map(item => model.UserModel.findOne({phone:item.phone},'name IDcard bank bankCard bank_area bank_name'));
                return Promise.all(promises);
            })
            .then((bankInfoList) => {//promise.all返回的结果是一一对应的
                for(let i=0; i<doc1.length; i++){
                    let obj = {};
                    
                    Object.assign(obj, JSON.parse(JSON.stringify(doc1[i])), JSON.parse(JSON.stringify(bankInfoList[i])));
                    result.push(obj);
                }
                return new Promise((resolve, reject) => {
                        resolve(result);
                })           
            })
            .then((result) => {
                return new Promise(() => {
                    res.json({ code: 0, msg: '查询成功', result: result});
                    return;
                });
            })
            .catch((e) => {
                console.log(e);
                res.json({ code: -1, msg: '查询失败'});
                return;
            });
    

    -------------------------------------------------Supplement---------- ---------------------------------------

    The idea of ​​counting is still achievable, just use the event module:

    reply
    0
  • 代言

    代言2017-06-29 10:11:23

    Since Promise is an asynchronous call, using return after all queries will return before the data is actually obtained, so you need to add a counter count in the Promise, and add a loop under all Promises. All docs have been cycled to (count == doc.length) before they can be output and returned.

    const deasync = require('deasync'); // 引入deasync包
    ...
    let result = []; //存放查询结果
    model.WithdrawModel.find({status: 'processing'}, (err, doc) => {
        if(err) {
            console.log(err);
            res.json({code: -1, msg: '查询失败'});
            return;
        } else {
            let count = 0, len = doc.length;
    
            doc.forEach((item, index) => {
                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)));
                        result.push(obj);
                        console.log(result); 
                    }
    
                    count++;
                });
            });
    
            deasync.loopWhile(() => count < len);
    
            res.json({code: 0, msg: '查询成功', result: result});
            return;
        }
    });

    reply
    0
  • Cancelreply