Skip to content

Promisify server.listen #21482

Description

@caub

Problem:

const server = app.listen();
console.log(`Server listening on: ${server.address().port}`)

can fail, as the server is created asynchronously and using the callback is not always practical/flexible

Proposal

either server.listenPromise(port), or even better, have server.listen(port) return a Promise if no callback is provided

Example

// .... 

const start = async () => {
    await config.load();
    await DB.connect(dbOptions);
    router(app);
    app.use((err, req, res, next) => { // error handler
        // ...
    });

    const server = http.createServer(app);
    // proposal:
    return server.listen(process.env.PORT || 3000); // if .listen would be a promise resolving to server
    // or await server.listen(...); return server; else

    // currently I have to do:
    // return new Promise((res, rej) => server.listen(process.env.PORT || 3000, err => err ? rej(err) : res()));

    // or using express's app.listen, which wraps createServer and listen:
    // return new Promise((res, rej) => app.listen(process.env.PORT || 3000, function (err) {
    //      if (err) return rej(err);
    //      res(this) // this is node's http Server
    // }));

    // using util.promisify doesn't look much better:
    // return promisify(server.listen).bind(server)(process.env.PORT || 3000);
    // or
    // return promisify(cb => server.listen(process.env.PORT || 3000, cb))();
};

then using it somewhere else:

start()
        .then(server => console.log(`Server listening on: ${server.address().port}`))
        .catch(err => {
           // ...
        });

Edit: I'll try to submit this request to express, and have a similar promise method near https://github.com/expressjs/express/blob/master/lib/application.js#L616-L619

Edit2: the discussion in expressjs/express#3675 has interesting details

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestIssues requesting new Node.js features.netIssues and PRs related to the net subsystem.staleIssues and PRs marked stale due to inactivity and scheduled for automatic closure.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions