Guest User

Untitled

a guest
Jul 18th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. ```js
  2. export const getNotifications = async (title) => {
  3. let ASYNC_TIMEOUT = 10000 // 10s
  4. let didTimeout = false
  5. let notifications = []
  6.  
  7. const workerDelayedPromise = () => {
  8. return new Promise(async (resolve, reject) => {
  9.  
  10. // timeout in order to send reject if delayed
  11. const timeout = setTimeout(() => {
  12. didTimeout = true
  13. reject('Request notifications timed out')
  14. }, ASYNC_TIMEOUT)
  15.  
  16. // clearTimeout and didTimeout to false
  17. const cleanTimeout = () => {
  18. clearTimeout(timeout)
  19. didTimeout = false
  20. }
  21.  
  22. // get current serviceWorker
  23. let worker = await serviceWorker
  24.  
  25. try {
  26. // get notifications was open in the navigator
  27. let response = await worker.getNotifications()
  28.  
  29. // running only if timeout(ASYNC_TIMEOUT) still exists
  30. cleanTimeout()
  31.  
  32. if (!didTimeout){
  33. resolve(response)
  34. }
  35. } catch (error) {
  36. reject(error)
  37. }
  38. })
  39. }
  40.  
  41. try {
  42. notifications = await workerDelayedPromise()
  43.  
  44. if (notifications.length <= 0) return []
  45.  
  46. if (title){
  47. return notifications.filter(item => {
  48. if (item.title == title){
  49. return item
  50. }
  51. })
  52. }
  53.  
  54. return notifications
  55. } catch (error) {
  56. console.error(error)
  57. return []
  58. }
  59. }
  60. ```
Add Comment
Please, Sign In to add comment