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