Created
October 30, 2020 11:16
-
-
Save suityou01/cfb51be8cc774a5ed4438c67e7953d4b to your computer and use it in GitHub Desktop.
Promises promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*Simple IIFE examples*/ | |
//https://developer.mozilla.org/en-US/docs/Glossary/IIFE | |
/* | |
(function(){ | |
console.log("I am an immediately invoked function expression, or IFFE"); | |
})(); | |
(()=>{ //NB It uses an arrow function '=>' | |
console.log("I am an immediately invoked anonymous function expression"); | |
})(); | |
*/ | |
/*Simple callback example*/ | |
/* | |
function callback(){ | |
console.log("I am the callback, coo coo ca choo"); | |
} | |
function dostuffandcallback(callbackptr){ | |
console.log("Doing stuff"); | |
setInterval(()=>{ | |
callbackptr(); | |
},2000); | |
} | |
dostuffandcallback(callback); | |
*/ | |
//A Promise has 2 callbacks typically referenced by resolve and reject | |
/* | |
let x= new Promise(function(resolve, reject){ //The function here is the executor, it is executed automatically when the Promise is created | |
//The executor has an 'arity' of 2. Both arguments are provided by the javascript engine, and are callbacks | |
resolve("Hi, good things happened"); //<<<< This is returned to the 'then' method of the promise, which is called automatically | |
}); | |
console.log(x); //This prints Promise { 'Hi, good things happened' } | |
x.then(value=>console.log(value)); //This prints Hi, good things happened | |
*/ | |
/*Simple promise example*/ | |
/* | |
async function dostuffandreturnpromise() { | |
return new Promise(resolve => setTimeout(resolve, 2000, "Hello World")); | |
} | |
dostuffandreturnpromise() //Not using await | |
.then((retval)=>{ //NB A promise is "thenable" | |
console.log(retval); | |
}); | |
(async ()=>{ //Using await | |
console.log(await dostuffandreturnpromise()); | |
})(); // <<<<<<< NB This is wrapped in an asynchronous IIFE | |
*/ | |
/*A promise returning a promise*/ | |
/* | |
function dostuffandreturnpromisesquared() { | |
return Promise.resolve({inner: () => Promise.resolve("Hello World")}); | |
//({}) <<<< This is an empty object inside some parentheses | |
//({inner: "A string"}) <<<< This is an object with one string property | |
//({inner: () => { return "Hello World"}}) <<<< This is an object with one property that is an anonymous function | |
//({inner: () => Promise.resolve("Hello World")}); <<<< This anonymous function just returns a promise | |
} | |
dostuffandreturnpromisesquared() //This returns the first promise | |
.then((retval=>retval.inner())) //The first promise returns the object with the inner property which references the anonymous function | |
.then(data=>{ //This is the resolved Promise returned from the inner anonymous function | |
console.log(data); | |
}) | |
.catch((error) => { //This fires if an error occurs in the Promise | |
console.error('Error:', error); | |
}) | |
.finally(()=>{ | |
console.log("Do clean up stuff here"); | |
}); | |
*/ | |
/*A promise doing something or timing out*/ | |
/* | |
console.log("Attempting task with timeout"); | |
const promise1 = new Promise((resolve, reject) => { | |
setTimeout(resolve, 1000, 'Pass'); | |
}); | |
const promise2 = new Promise((resolve, reject) => { | |
setTimeout(reject, 2000, 'Fail'); | |
}); | |
Promise.race([promise1, promise2]) | |
.then((value) => { | |
console.log(value); | |
// Both resolve, but promise2 is faster | |
}).catch((error)=>{ | |
console.log(error); | |
}); | |
*/ | |
//A promise is a state machine also | |
/* | |
let starttime = Date.now(); | |
let waittime = 5000; | |
const p = new Promise((resolve, reject) => { | |
setTimeout(resolve, waittime, 'Pass'); | |
}); | |
p | |
.then((retval)=>{ | |
console.log(retval); | |
console.log(this); | |
}); | |
while(Math.abs(Date.now() - starttime) < waittime){ | |
console.log(p); | |
} | |
*/ | |
//When you put the async keyword infront of a function, then the function automatically returns a promise | |
/* | |
async function myasyncfunction(){ | |
return "Hello World"; | |
} | |
console.log(myasyncfunction); | |
console.log(myasyncfunction()); | |
*/ | |
//Error handling an asynchronous function | |
/* | |
async function myasyncfunction(){ | |
throw new Error("Hello World"); | |
return "Hello World"; | |
} | |
myasyncfunction() | |
.then(()=>{ | |
console.log("It worked just fine"); | |
}) | |
.catch((error)=>{ | |
console.log("Caught the error"); // <<<< It automatically returns a rejected promise in a fail case | |
}) | |
*/ | |
//All settled (one way or another, I'm gonna getcha getcha getcha) | |
/* | |
console.log("Waiting for all promises to settle"); | |
const promise1 = new Promise((resolve, reject) => { | |
setTimeout(resolve, 2000, 'Pass'); | |
}); | |
const promise2 = new Promise((resolve, reject) => { | |
setTimeout(reject, 5000, 'Fail'); | |
}); | |
const promises = [promise1, promise2]; | |
Promise.allSettled(promises). | |
then((results) => results.forEach((result) => console.log(result.status))); | |
*/ | |
//All promise resolves while others reject | |
/* | |
console.log("Waiting for all promises to "); | |
const promise1 = new Promise((resolve, reject) => { | |
setTimeout(resolve, 5000, 'Pass'); | |
}); | |
const promise2 = new Promise((resolve, reject) => { | |
setTimeout(reject, 2000, 'Fail'); | |
}); | |
const promises = [promise1, promise2]; | |
Promise.all(promises) | |
.then((value) => { console.log('A promise fulfilled') }) //This doesn't fire as one of the promises rejects | |
.catch((error)=>{ console.log('A promise rejected')}); //Only this fires, as an when the rejection happens as this is the last promise to complete | |
*/ | |
//Promise.any is currently experimental and won't work with this version of node | |
//Generator function | |
/* | |
function* mygenerator(){ | |
yield 1; | |
yield 2; | |
} | |
let x = mygenerator(); | |
console.log(x.next()); | |
console.log(x.next()); | |
console.log(x.next()); | |
*/ | |
//Promise called from generator function | |
/* | |
const fetchSomething = () => new Promise((resolve) => { | |
resolve(Date.now()); | |
}); | |
function* repeater(i){ | |
for(let n=0; n<i; n++){ | |
yield fetchSomething(); | |
} | |
} | |
let x = repeater(3); | |
console.log(x.next()); | |
console.log(x.next()); | |
console.log(x.next()); | |
console.log(x.next()); | |
*/ | |
//Promise chaining | |
/* | |
let p = new Promise((resolve, reject) => { | |
setTimeout(() => { | |
resolve(10); | |
}, 300); //This resolves once after 300ms | |
}); | |
p.then((result) => { | |
console.log(result); // 10 | |
return result * 2; | |
}).then((result) => { | |
console.log(result); // 20 | |
return result * 3; | |
}).then((result) => { | |
console.log(result); // 60 | |
return result * 4; | |
}); | |
*/ | |
//We see this pattern when fetching | |
/* | |
let fakejson = { | |
person_id: 1, | |
name: 'Fairfax Carstairs' | |
}; | |
function fakeapiresponse() { | |
return Promise.resolve({json: () => Promise.resolve(fakejson)}); | |
} | |
let fakefetch = (url) => { | |
return fakeapiresponse(); | |
} | |
fakefetch('http://thisurldoesnotexist/somethingelsemadeup') | |
.then(response => response.json()) | |
.then(data => console.log(data)); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment