Skip to content

Instantly share code, notes, and snippets.

@christophemarois
Created January 13, 2018 15:49
Show Gist options
  • Save christophemarois/c5d888513aa4e65c21677b25338456a4 to your computer and use it in GitHub Desktop.
Save christophemarois/c5d888513aa4e65c21677b25338456a4 to your computer and use it in GitHub Desktop.
Async properties in JS Class constructor
// 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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment