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?
Ask and answer your own questions, and receive guidance from others.
promise.all is implemented as follows:
-------------------------------------------------Supplement---------- ---------------------------------------
The idea of counting is still achievable, just use the event module:
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.