Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 971
Tiago Bértolo Avatar asked Oct 25 '17 13:10

Tiago Bértolo


People also ask

Does async await work with callbacks?

The await keyword is used in an async function to ensure that all promises returned in the async function are synchronized, ie. they wait for each other. Await eliminates the use of callbacks in .

How do you turn a callback into a promise?

If the callback function returns non-error output, we resolve the Promise with the output. Let's start by converting a callback to a promise for a function that accepts a fixed number of parameters: const fs = require('fs'); const readFile = (fileName, encoding) => { return new Promise((resolve, reject) => { fs.

Does await unwrap a promise?

Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

What is async wrapper?

#javascript #pattern. Reusable function to run any Promise that returns an array of data and error. Using Async/Await is great, but when working with multiple Promises it often clutters your code with multiple try/catch statements.


1 Answers

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));
like image 143
guest271314 Avatar answered Oct 11 '22 12:10

guest271314