Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  98] [ 3]  / answers: 1 / hits: 26801  / 7 Years ago, wed, october 25, 2017, 12:00:00

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?


More From » node.js

 Answers
18

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

[#56121] Monday, October 23, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryantc

Total Points: 455
Total Questions: 96
Total Answers: 110

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
bryantc questions
Fri, Aug 13, 21, 00:00, 3 Years ago
Tue, Mar 30, 21, 00:00, 3 Years ago
Fri, Jun 5, 20, 00:00, 4 Years ago
Wed, May 27, 20, 00:00, 4 Years ago
;