0

I'm trying to write the following code into a es2015 class syntax:

export function initialize(port) {
    return new Promise((resolve, reject) => {
        const application = express();
        const server = application.listen(port, function listening(error) {
            if (error) reject(error);
            resolve(server);
        });
    });
}
const server = async initialize(port);

es2015:

class Server {
    constructor(port) {
        return new Promise((resolve, reject) => {
            const application = express();
            const server = application.listen(port, function listening(error) {
                if (error) reject(error);
                resolve(server);
            });
        });
    }
}
const server = async new Server(port); // <-- not a good idea!

Apparently returning and a Promise is not such a good idea when using the new which should return an instant instance. Any ideas?

basickarl
  • 37,187
  • 64
  • 214
  • 335
  • 1
    Did you mean `await` instead of `async` after `const server =`? – Bergi Nov 29 '19 at 14:07
  • "*I'm trying to write the following code into a es2015 class syntax*" - why? There's no point in doing that. It doesn't even work as you noticed. The `function` is much simpler. What was your goal? – Bergi Nov 29 '19 at 14:08

1 Answers1

0

You could use a separate initialise method and call that from instance:

class Server {
  constructor(port) {
    this.port = port;
  }

  initialise() {
    return new Promise((resolve, reject) => {
      const application = express();
      const server = application.listen(this.port, function listening(error) {
        if (error) reject(error);
        resolve(server);
      });
    });
  }
}
const server = new Server(port);
server.initialise().then(() => // do some stuff)

Clarity
  • 10,730
  • 2
  • 25
  • 35
  • What's the advantage of doing that? It's not like you can reuse `serverInstance` by calling `initialise()` a second time or so. – Bergi Nov 29 '19 at 14:10
  • This avoids creating a promise in constructor. – Clarity Nov 29 '19 at 14:14
  • Sure, I mean it's even a good solution for that, but what's the advantage of using a `class Server` over the original code? – Bergi Nov 29 '19 at 14:17