Rumah > Soal Jawab > teks badan
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;
}
});
Menggelung melalui pertanyaan, hasil di atas secara langsung mengembalikan nilai nol Bagaimana saya boleh memastikan semua pertanyaan dalaman dalam doc.map diselesaikan sebelum mengeluarkan nilai hasil?
仅有的幸福2017-06-29 10:11:23
Tanya dan jawab soalan anda sendiri, dan dapatkan bimbingan daripada orang lain.
janji.semuanya dilaksanakan seperti berikut:
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---------- ----------------------------------------
Idea untuk mengira masih boleh dicapai, hanya gunakan modul acara:
代言2017-06-29 10:11:23
Memandangkan Promise ialah panggilan tak segerak, gunakan return
,会在还没真正获取到数据之后就返回,所以需要Promise内添加一个计数器count,在所有的Promise下,加一个循环,当所有的doc都循环到了(count == doc.length
) selepas semua pertanyaan untuk mengeluarkan pulangan.
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;
}
});