与async.parallel斗争

时间:2018-12-21 11:44:48

标签: javascript express asynchronous ejs

我正在尝试将一些mongodb结果堆叠起来,然后再将其全部交付给ejs。我认为我还不太了解async.parallel的技巧...任何指针都将不胜感激!

也许最好对此脚本进行进一步的异步/等待调查?

我对此很陌生-如您所知-我不确定我的路线是否很好...

const express = require('express');
const app = express();
const async = require('async');
const format = require('date-fns/format');
const norskDato = require('date-fns/locale/nb');
app.set('view engine', 'ejs');

// ------------------ START MONGODB-CONNECTION -------------------------------
const MongoClient = require('mongodb').MongoClient;
var db; 

MongoClient.connect(mongo_connection, (err, client) => {
    console.log('MongoClient.connect');
    if(err) { return console.log(err); }
    db = client.db(database);
    // Express serverstart
    app.listen(port, function() {
        console.log("Jonas sin Express-server!");
    });
    });

// Define today start and end
var start = new Date();
start.setHours(0,0,0,0);
var slutt = new Date();
slutt.setHours(23,59,59,999);

// Stack up results from mongodb queries
var stack = {};

// First query
stack.scandic_enk_std = function(callback){
    var query = {skaptdato: {$gte: start, $lt: slutt}, personer: 1, romtype: {$ne: "Non-refundable"} };
    var order = { romnavn: 1, fradato: 1};
    app.get('/revMan/query', (req, res) => { 
        db.collection('scandic_priser').find(query).sort(order).toArray((err, result) => {
        if (err) return console.log(err)        
        callback(err, result);
        });
    });
};

// second query
// ... will be made when the first one actually works

// Render to ejs
async.parallel(stack, function(err, result) {
    //console.log("Stack:" + stack);  || This logs the stack and it looks good
    console.log(result); // logs the result and it looks great
    app.get(mappe, (req, res) => {  
        res.render('index', result ); // index.ejs is dead/empty
    });
});

0 个答案:

没有答案