Guest User

Untitled

a guest
Jan 23rd, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. // For demonstration purposes
  2. async function getHTML () {
  3. if (Math.random() > 0.5) {
  4. return 'Randomly succeeded'
  5. } else {
  6. throw new Error('Randomly failed')
  7. }
  8. }
  9.  
  10. // Checks that an instance promise didn't resolve with an error,
  11. // and throw it if did, enabling the use of try {} catch (err) {}
  12. // in async function
  13. async function ensureResolved (prop) {
  14. const value = await prop
  15. if (value instanceof Error) {
  16. throw value
  17. } else {
  18. return value
  19. }
  20. }
  21.  
  22. class Foo {
  23. // Make this.res a promise that will always resolve, either
  24. // with the result, or the error it originally rejected.
  25. constructor () {
  26. this.res = getHTML().catch(err => Promise.resolve(err))
  27. }
  28.  
  29. // Make an async function that ensures this.res didn't reject
  30. // with an error, and either return the result or throw an error.
  31. async getRes () {
  32. return ensureResolved(this.res)
  33. }
  34. }
  35.  
  36. // Usage example
  37. const foo = new Foo()
  38. foo.getRes()
  39. .then(res => console.log('succeeded', res))
  40. .catch(err => console.error('failed', err))
Add Comment
Please, Sign In to add comment