在使用异步序列时,我先在下面得到代码,首先查询车辆列表,然后从车辆结果中使用VIN,然后用它查询文件和卡盘列表,但无法获取locals.data。 images_gallery,因为它在获取locals.data.images_gallery结果之前先渲染页面,这就是我无法将数据传递给视图(html)的原因。关于locals.data.vehicle结果没有问题,我可以将数据渲染到视图中,问题出在locals.data.images_gallery上,因为渲染晚了。
您可以在代码上看到,首先在控制台日志1之前呈现控制台日志2。
如下面的屏幕截图所示,调用脚本时,首先调用控制台日志2,其长度为0,而日志1的长度为13,这就是为什么呈现页面时空数据。 here
这种样式有什么问题?有什么办法吗?像是因为异步调用?
我只想获取locals.data.images_gallery。但是当脚本呈现为空时。因为locals.data.images_gallery.length渲染晚了
view.on('init', function (next) {
async.series([
function (next) {
keystone.list('Vehicle').model.findOne()
.where('state', 'published')
.where('VIN', "5FNYF28677B037628")
.exec(function (err, vehicle) {
if (err) {
console.log('Error finding current user Vehicles', err);
}
if (vehicle) {
locals.data.vehicle = vehicle;
}
return next(err);
});
},
function (next) {
var docs_ids = []
MongoClient.connect(url, function (err, client) {
if (err) {
return res.render('index',
{
title: 'Uploaded Error',
message: 'MongoClient Connection error', error: err.errMsg
});
}
const db = client.db(dbName);
const collection = db.collection('fs.files');
const collectionChunks = db.collection('fs.chunks');
collection.find({ metadata: locals.data.vehicle.VIN }).toArray(function (err, docs) {
if (err) {
return res.render('index', {
title: 'File error',
message: 'Error finding file',
error: err.errMsg
});
}
if (!docs || docs.length === 0) {
return res.render('index', {
title: 'Download Error',
message: 'No file found'
});
} else {
for (let i = 0; i < docs.length; i++) {
docs_ids.push(docs[i]._id)
}
collectionChunks.find({ files_id: { $in: docs_ids } })
.sort({ n: 1 }).toArray(function (err, chunks) {
if (err) {
return res.render('index', {
title: 'Download Error',
message: 'Error retrieving chunks',
error: err.errmsg
});
}
if (!chunks || chunks.length === 0) {
return res.render('index', {
title: 'Download Error',
message: 'No data found'
});
}
let fileData = [];
for (let i = 0; i < chunks.length; i++) {
locals.data.images_gallery.push('data:' + docs[0].contentType + ';base64,'
+ chunks[i].data.toString('base64'));
}
console.log("LOG 1 " , locals.data.images_gallery.length)
return next();
});
}
})
})
},
], function (err) {
if (err) {
locals.data.err = err
}
locals.data.results = locals.data
next();
})
console.log("LOG 2" , locals.data.images_gallery.length)