Last active
January 22, 2017 13:38
-
-
Save adambene/1da05053b6508f2998d006481aa5d730 to your computer and use it in GitHub Desktop.
Exception handling in ES6
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
// define an async operation that rejects if the path is not a string | |
const someAsyncOperation = async (path) => { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
if (typeof path === 'string') { | |
resolve(`Hello Panda! Path is = ${path}`); | |
} else { | |
reject(new Error(`Path is not a string. Path (${typeof path}) = ${path}`)); | |
} | |
}, 1000); | |
}); | |
}; | |
// handle exceptions the ES6 way with async-await | |
(async () => { | |
try { | |
const res = await someAsyncOperation(321); | |
console.log(res); | |
} catch (error) { | |
console.error('(FROM ASYNC/AWAIT) Error cause is:', error); | |
} | |
})(); | |
// or the same the promise way | |
(() => { | |
someAsyncOperation(123) | |
.then((res) => { | |
console.log(res); | |
}) | |
.catch((error) => { | |
console.error('(FROM PROMISE) Error cause is:', error); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment