我有一个函数,它通过id查找Release,它返回一个promise。 但在第二次发布没有定义。我不明白为什么。 有人可以解释并建议代码编辑。我真的很困惑。
我的代码
var findReleaseById = function(id) {
return Release.find({ _id: id }).select('releasedate').exec()
.then(releaseArray => Array.isArray(releaseArray) ? releaseArray[0] : undefined)
.then(release ? release.releasedate : undefined)
}
给我
ReferenceError: release is not defined
[编辑1]
上面的功能是一个更大的功能。此函数计算2个版本之间的差异
exports.release_difference = (req, resp, next) => {
const relid1 = req.query.rel1;
const relid2 = req.query.rel2;
var findFeatures = function(releases) {
const promises = releases.map(release =>
Feature.find({
'release._id': release._id
}).select('name description release').exec()
)
return Promise.all(promises)
.then(featureArrayArray => featureArrayArray.filter(featureArray => Array.isArray(featureArray)))
.then(featureArrayArray => [].concat(featureArrayArray))
.catch(error => {});
}
var findChanges = function(releases) {
const promises = releases.map(release =>
Change.find({
'release._id': release._id
}).select('name description relatedFeature release').exec()
)
return Promise.all(promises)
.then(changeArrayArray => changeArrayArray.fill(changeArray => Array.isArray(changeArray)))
.then(changeArrayArray => [].concat(changeArrayArray))
.catch(error => {});
}
var makepdf = function(features, changes, releasess, template, options, cb) {
pdfcreator.makepdf(features, changes, releasess, template, options, function(res) {
cb(res.filename);
});
}
var findReleaseById = function(id) {
return Release.find({
_id: id
}).select('releasedate').exec()
.then(releaseArray => Array.isArray(releaseArray) ? releaseArray[0] : undefined)
.then(release => release ? release.releasedate : undefined)
}
const releasedate1Promise = findReleaseById(relid1);
const releasedate2Promise = findReleaseById(relid2);
Promise.all(releasedate1Promise, releasedate2Promise)
.then(([releasedate1, releasedate2]) => {
return Release.find({
'releasedate': {
'$gt': releasedate1,
'$lte': releasedate2
}
}).sort('version').exec()
})
.then(releasesBetween => {
const fsPromise = findFeatures(releasesBetween);
const csPromise = findChanges(releasesBetween);
return Promise.all(fsPromise, csPromise)
})
.then(([fs, cs]) => {
makepdf(fs, cs, releasesBetween, template, options, function(file) {
resp.download(file);
});
});
}
答案 0 :(得分:1)
在这一行:
.then(release?release.releasedate:undefined)
release
是undefined
。您需要在函数中将其作为参数接收:
.then(release => release ? release.releasedate : undefined)