【发布时间】:2017-11-27 14:42:09
【问题描述】:
我需要知道如何使用 Promises 在 forEach 循环之后返回一个值。在这一刻,当我启动我的主程序时,我得到:
[ Promise { <pending> }, Promise { <pending> } ]
(我的 sampleidlist 只包含 2 条记录) 这是我的代码:
MongoClient.connect("mongodb://127.0.0.1/myproject", function(err, db) {
return db.collection('RUN').find({
"idRun": query.idRun
}).toArray()
.then((out) => {
var sampleidlist = out[0].SAMPLE_ID
var pazlist = []
// Promisearr is the array of promises where I try to push the promises
var Promisearr = []
// there is the function find_paz that return idPaz for every sampleId in sampleidlist
function find_paz(sampleid) {
// I return a new Promise for every sampleId
// I want to create an array of idPaz
return new Promise((resolve, reject) => {
db.collection('PATIENTS').find({
"SAMPLE_ID": sampleid
}).toArray()
.then((pazArr) => {
var singlepaz = []
singlepaz.push(pazArr[0].idPaz)
return singlepaz
})
.then((singlepaz) => {
pazlist.push(singlepaz)
})
})
}
// Here the forEach loop
sampleidlist.forEach(sampleid => {
Promisearr.push(
find_paz(sampleid)
)
})
Promise.resolve(Promisearr)
.then(Promise.all(Promisearr))
.then(value => {
// value return {promise<pending>}
// I want that value is the array of idPaz
console.log(value)
}).catch((err) => {
console.log('errored', err);
})
}).catch((err) => {
console.log('errored', err);
})
})
有什么建议吗? 非常感谢:)
【问题讨论】:
-
您需要解决或拒绝
find_paz中的每个promise,并且只在promise 数组上使用Pomise.all()
标签: javascript mongodb foreach promise