Skip to content

Instantly share code, notes, and snippets.

View rajatjain-21's full-sized avatar
💭
Alive in the world of code

Rajat Jain rajatjain-21

💭
Alive in the world of code
View GitHub Profile
// This implementation does not work with Symbols, BigInts
function stringify(data) {
if (data === undefined)
return undefined
if (data === null)
return 'null'
if (data.toString() === "NaN")
return 'null'
if (data === Infinity)
function PromisePolyfill(executor) {
let onResolve, onReject;
let fulfilled = false,
rejected = false,
called = false,
value;
function resolve(v) {
fulfilled = true;
value = v;
@rajatjain-21
rajatjain-21 / promise1.js
Last active September 8, 2022 03:11
Promise example
// -------------------------------------------------------------------
// this function simulates a request that needs to run async
// -------------------------------------------------------------------
function favoriteBlogger(favorite) {
return new Promise((resolve, reject) => {
if (favorite === 'rajatexplains') {
resolve(favorite);
} else {
reject('your preference is poor😛');
// -------------------------------------------------------------------
// this function simulates a request that needs to run async
// -------------------------------------------------------------------
function doOtherAsyncThing() {
return new Promise((resolve) => {
setTimeout(() => resolve('it’s done!'), 500);
});
}
@rajatjain-21
rajatjain-21 / async1.js
Created September 8, 2022 03:13
Async Example
async function getData() {
// using await means the resolved value of the Promise is returned!
const response = await fetch('https://blogger.ceo/api/blogs/image/random').then(
(response) => response.json(),
); // .then still works when it makes sense!
const otherResponse = await doOtherAsyncThing();
// do stuff with `response` and `otherResponse`