meteorhacks / picker

Server Side Router for Meteor
MIT License
182 stars 30 forks source link

How to send async response? #46

Open trusktr opened 7 years ago

trusktr commented 7 years ago

I can't seem to send an async response. For example, I'm trying

for (const route of routes) {
    Picker.route(`/${route}`, function(params, req, res, next) {
        console.log(' ---- route: ', route)
        const appDir = getAppPath()
        const html = fs.readFileSync(path.resolve(appDir, 'public', 'pages', route, 'index.html'), function() {
            console.log('  -- sending response.')
            res.writeHead(200, {'Content-Type': 'text/html'})
            res.end(html)
        })
    })
}

The async logic fires, but the client doesn't get the response. I'm guessing this is because the res.writeHead and res.end calls are happening after the route handler has returned.

How do we make this work?

The reason I want async is because I think it may perform better with multiple requests (any thoughts on that?). For example, here's the sync version, which works:

for (const route of routes) {
    Picker.route(`/${route}`, function(params, req, res, next) {
        console.log(' ---- route: ', route)
        const appDir = getAppPath()
        const html = fs.readFileSync(path.resolve(appDir, 'public', 'pages', route, 'index.html'))
        console.log('  -- sending response.')
        res.writeHead(200, {'Content-Type': 'text/html'})
        res.end(html)
    })
}
trusktr commented 7 years ago

I know I can use wrapAsync, but I think that defeats the purpose of intentionally doing things async.