Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // For demonstration purposes
- async function getHTML () {
- if (Math.random() > 0.5) {
- return 'Randomly succeeded'
- } else {
- throw new Error('Randomly failed')
- }
- }
- // Checks that an instance promise didn't resolve with an error,
- // and throw it if did, enabling the use of try {} catch (err) {}
- // in async function
- async function ensureResolved (prop) {
- const value = await prop
- if (value instanceof Error) {
- throw value
- } else {
- return value
- }
- }
- class Foo {
- // Make this.res a promise that will always resolve, either
- // with the result, or the error it originally rejected.
- constructor () {
- this.res = getHTML().catch(err => Promise.resolve(err))
- }
- // Make an async function that ensures this.res didn't reject
- // with an error, and either return the result or throw an error.
- async getRes () {
- return ensureResolved(this.res)
- }
- }
- // Usage example
- const foo = new Foo()
- foo.getRes()
- .then(res => console.log('succeeded', res))
- .catch(err => console.error('failed', err))
Add Comment
Please, Sign In to add comment