Tiago Bértolo
Tiago Bértolo

Reputation: 4373

How do I wrap a callback with async await?

My function returns a promise that resolves as soon as the HTTP server starts. This is my code:

function start() {
    return new Promise((resolve, reject) {
        this.server = Http.createServer(app);
        this.server.listen(port, () => {
            resolve();
        });
    })
}

How do I convert the start function to async/await?

Upvotes: 18

Views: 29661

Answers (5)

Damaged Organic
Damaged Organic

Reputation: 8467

This is something I've stumbled upon when while trying to make the HTTP server listen function truly promisified. The biggest problem is not to resolve on listening callback, but to handle the errors on startup.

Wrapping in Promise and attempt to catch (as other answers suggest) or try-catch block won't have any effect, because any Node.js server, net or derived http/https, are EventEmitter instances, which means no errors are thrown. Instead, they are emitted as the error event.

So, considering all of the above, correct implementation of promisified server listen function is as follows:

const { createServer } = require('http');

const server = createServer();

const listen = async (port, host) => {
  return new Promise((resolve, reject) => {
    const listeners = {};

    listeners.onceError = (error) => {
      server.removeListener('listening', listeners.onceListening);
      reject(error);
    };

    listeners.onceListening = () => {
      server.removeListener('error', listeners.onceError);
      resolve();
    };

    server
      .prependOnceListener('error', listeners.onceError)
      .prependOnceListener('listening', listeners.onceListening);

    server.listen(port, host);
  });
}

Reject and resolve calls inside handlers are prepended to the top of the listeners stack, and they mutually cancel each other - whoever fires first.

That way it's guaranteed that the listen method will either start the server or throw a catchable error.

Upvotes: 2

TOPKAT
TOPKAT

Reputation: 8698

I created a basic utility that may not be the most proper way to do, but it is way more readable, in my opinion:

// Async time-out utility
const timeout = async ms => new Promise(res => setTimeout(res, ms));

async function start() {
    let output;

    this.server = Http.createServer(app);
    this.server.listen(port, () => {
        output = true; // Or can be any data that you want to return
    });
    while (output === undefined) await timeout(10);
    return output;
}

This is the basic concept. However be careful if your promise may return undefined values has the function will run forever (but this will not crash).

Upvotes: -1

guest271314
guest271314

Reputation: 1

Include async before the function declaration and await the Promise constructor. Though note, you would essentially be adding code to the existing pattern. await converts a value to a Promise, though the code in the question already uses the Promise constructor.

async function start() {
    let promise = await new Promise((resolve, reject) => {
        this.server = Http.createServer(app);
        this.server.listen(port, () => {
            resolve();
        });
    })
    .catch(err => {throw err});

    return promise
}

start()
.then(data => console.log(data))
.catch(err => console.error(err));

Upvotes: 19

Kasia
Kasia

Reputation: 1735

Use:

const doRequest = () => new Promise((resolve, reject) {
    this.server = Http.createServer(app);
    this.server.listen(port, () => {
        resolve();
    });
})

async function start() {
    await doRequest()
}

Something like this, I believe.

Upvotes: 5

JoshWillik
JoshWillik

Reputation: 2645

Creating a new Promise like the other answers suggest works fine in this case, but as a general rule, util.promisify can stop you from writing the same thing many times.

So you can do something like this instead: (node.js v8.0.0+)

const util = require('util');
async function start() {
    let server = Http.createServer(app);
    await util.promisify(server.listen.bind(server))(port);
}

util.promisify(some_function) takes a function which normally accepts a callback, and returns a new, wrapped version of this function that instead returns a promise.

With more explained steps:

let server = Http.createServer(app);
// .bind() is needed so that .listen() keeps the correct `this` context when it is called.
// If your function does not require any specific context, leave off .bind()
let listen_promise = util.promisify(server.listen.bind(server));
await listen_promise(port);

More advanced promisification can be done with bluebird.

Upvotes: 12

Related Questions