export const getNotifications = async (title) => {
let ASYNC_TIMEOUT = 10000 // 10s
let didTimeout = false
let notifications = []
const workerDelayedPromise = () => {
return new Promise(async (resolve, reject) => {
// timeout in order to send reject if delayed
const timeout = setTimeout(() => {
didTimeout = true
reject('Request notifications timed out')
}, ASYNC_TIMEOUT)
// clearTimeout and didTimeout to false
const cleanTimeout = () => {
clearTimeout(timeout)
didTimeout = false
}
// get current serviceWorker
let worker = await serviceWorker
try {
// get notifications was open in the navigator
let response = await worker.getNotifications()
// running only if timeout(ASYNC_TIMEOUT) still exists
cleanTimeout()
if (!didTimeout){
resolve(response)
}
} catch (error) {
reject(error)
}
})
}
try {
notifications = await workerDelayedPromise()
if (notifications.length <= 0) return []
if (title){
return notifications.filter(item => {
if (item.title == title){
return item
}
})
}
return notifications
} catch (error) {
console.error(error)
return []
}
}
Last active
July 20, 2018 07:42
-
-
Save thadeu/3b084322fe1f0362b4cd2ce17a7d89e2 to your computer and use it in GitHub Desktop.
Promise Reject Delayed
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a bit of code review for ya 😄