How do i wrap a callback with async await?

Tiago Bértolo picture Tiago Bértolo · Oct 25, 2017 · Viewed 18.4k times · Source

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?

Answer

guest271314 picture guest271314 · Oct 25, 2017

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 at Question already uses 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));