Skip to content

Commit

Permalink
Convert async IIFE into promise-chain
Browse files Browse the repository at this point in the history
  • Loading branch information
eps1lon committed Oct 11, 2020
1 parent 23684a7 commit a3a0b3d
Showing 1 changed file with 24 additions and 30 deletions.
54 changes: 24 additions & 30 deletions docs/src/modules/components/Notifications.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,6 @@ import Divider from '@material-ui/core/Divider';
import { getCookie } from 'docs/src/modules/utils/helpers';
import { ACTION_TYPES } from 'docs/src/modules/constants';

function sleep(delay) {
return new Promise((resolve) => {
setTimeout(resolve, delay);
});
}

const useStyles = makeStyles((theme) => ({
paper: {
transformOrigin: 'top right',
Expand Down Expand Up @@ -96,33 +90,33 @@ export default function Notifications() {
return undefined;
}

(async () => {
await sleep(1500); // Soften the pressure on the main thread.
let newMessages;
try {
const result = await fetch(
'https://raw.githubusercontent.com/mui-org/material-ui/master/docs/notifications.json',
);
newMessages = await result.json();
} catch (err) {
// Swallow the exceptions, e.g. rate limit
}

if (active) {
const seen = getCookie('lastSeenNotification');
const lastSeenNotification = seen === '' ? 0 : parseInt(seen, 10);

dispatch({
type: ACTION_TYPES.NOTIFICATIONS_CHANGE,
payload: {
messages: newMessages || [],
lastSeen: lastSeenNotification,
},
// Soften the pressure on the main thread.
const timeout = setTimeout(() => {
fetch('https://raw.githubusercontent.com/mui-org/material-ui/master/docs/notifications.json')
.then((response) => {
return response.json();
})
.catch(() => {
// Swallow the exceptions, e.g. rate limit
return [];
})
.then((newMessages) => {
if (active) {
const seen = getCookie('lastSeenNotification');
const lastSeenNotification = seen === '' ? 0 : parseInt(seen, 10);
dispatch({
type: ACTION_TYPES.NOTIFICATIONS_CHANGE,
payload: {
messages: newMessages || [],
lastSeen: lastSeenNotification,
},
});
}
});
}
})();
}, 1500);

return () => {
clearTimeout(timeout);
active = false;
};
}, []);
Expand Down

0 comments on commit a3a0b3d

Please sign in to comment.