Skip to content

Instantly share code, notes, and snippets.

@saiumesh535
Last active February 8, 2018 23:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saiumesh535/fc6421bf3b025d50982f4462cabecf90 to your computer and use it in GitHub Desktop.
Save saiumesh535/fc6421bf3b025d50982f4462cabecf90 to your computer and use it in GitHub Desktop.
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