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
@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`
// -------------------------------------------------------------------
// 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 / 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😛');
function PromisePolyfill(executor) {
let onResolve, onReject;
let fulfilled = false,
rejected = false,
called = false,
value;
function resolve(v) {
fulfilled = true;
value = v;
// 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)
const input = [
1, 2, 3,
[4],
[5, 6, [7], [8, [9, [10]]]],
11, 12, 13,
[14, [[[[[15, [16]]]]]]],
17, 18,
[19, [20, [21, [22, [23, [24, [[[[[25]]]]]]]]]]]
];
class MyPromise {
static all(promises) {
let results = []; // to be resolved array of values
let completedPromises = 0;
// return a promise
return new Promise((resolve, reject) => {
promises.forEach((promise, index) => {
promise.then((value) => {
results[index] = value;
completedPromises += 1;
Function.prototype.bind = function(...args) {
let obj = this;
let params = args.slice(1);
return function(...args2) {
obj.apply(args[0], [...params, ...args2]);
}
}
let obj = {
a: 32,
b: 34
}
Object.defineProperty(obj, Symbol.iterator, {
configurable: false,
enumerable: false,
writable: false,
value: function() {
function normalFunc(x,y,callback) {
const result = x + y;
callback(result);
}
async function run() {
const promisedFn = promisify(normalFunc);
const result = await promisedFn(4,3).then(data => data*data);
console.log(result);
}
run()