javascriptnode.jsecmascript-6ecmascript-2017

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?


Solution

  • 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));