Skip to content

Instantly share code, notes, and snippets.

@saiumesh535
Last active Feb 8, 2018
Embed
What would you like to do?
Async await without try catch
// traditional way of writing code
const router = require('express').Router();
router.get('/check', check);
module.exports = router;
async function check(req, res) {
someOtherFunction().then((a) => {
somethingElseFunction().then((b) => {
res.status(200).json({a: a, b: b});
}).catch((error) => {
res.send("error");
})
}).catch((error) => {
res.send("error");
})
}
someOtherFunction = () => {
return new Promise((resolve, reject) => {
setTimeout(function () {
resolve("something")
}, 10);
})
}
somethingElseFunction = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("not a error");
})
})
}
// on introduction of async await with try and catch
const router = require('express').Router();
router.get('/check', check);
module.exports = router;
async function check(req, res) {
try {
const a = await someOtherFunction();
const b = await somethingElseFunction();
} catch (error) {
res.send(error.stack);
}
}
someOtherFunction = () => {
return new Promise((resolve, reject) => {
setTimeout(function () {
reject("something")
}, 10);
})
}
somethingElseFunction = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error("ssksks"))
})
})
}
// async await without try catch (recommended)
const router = require('express').Router();
router.get('/check', check);
module.exports = router;
async function check(req, res) {
const a = await someOtherFunction().catch((error) => {res.send("some error")});
const b = await somethingElseFunction().catch((error) => {res.send(("some error ", error))});
if (a && b) res.status(200).json({a: a,b: b});
}
someOtherFunction = () => {
return new Promise((resolve, reject) => {
setTimeout(function () {
resolve("something")
}, 10);
})
}
somethingElseFunction = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("from b");
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment