Skip to content

How to send async response? #46

@trusktr

Description

@trusktr

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)
    })
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions