Last active
February 8, 2018 23:01
-
-
Save saiumesh535/fc6421bf3b025d50982f4462cabecf90 to your computer and use it in GitHub Desktop.
Async await without try catch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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