expressjs async await code example
Example 1: node js request async await
function doRequest(url) {
return new Promise(function (resolve, reject) {
request(url, function (error, res, body) {
if (!error && res.statusCode == 200) {
resolve(body);
} else {
reject(error);
}
});
});
}
// Usage:
async function main() {
let res = await doRequest(url);
console.log(res);
}
main();
Example 2: expressjs async await
app.post('/signup', async(req, res) => {
try {
const { email, firstName } = req.body
const user = new User({ email, firstName })
const ret = await user.save()
res.json(ret)
} catch (error) {
console.log(error)
}
})
Example 3: expressjs4 async
app.post('/signup', async(req, res, next) => {
async function runAsync () {
await firstThing()
await secondThing()
}
runAsync()
.catch(next)
})