You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
constgetDinosaur=(name)=>{returnnewPromise((resolve,reject)=>{resolve({name})})}//Shorthand for synchronous values as a PromiseconstgetDinosaur=(name)=>Promise.resolve({name})constgetDinosaur=(name)=>Promise.reject(newError("Dinosaurs went extinct!")
//Warning: Modifies the Promise prototypePromise.prototype.always=function(onSettled){returnthis.then((value)=>Promise.resolve(onSettled()).then(()=>value),(reason)=>onSettled().then(()=>Promise.reject(reason)))}takeALongTimeToLoad().always(hideLoadingIndicator)
constgetData=()=>Promise.reject(newError('Connection Timed Out'))constgetCachedData=()=>Promise.resolve({name: 'Brontosaurus'})constlog=(value)=>console.log(value)getData().catch(getCachedData)//Could get data from localStorage.then(log)
Can be used any time an external resource isn't reliable
Fanning
Taking a Promise and independently calling multiple .then() on it
constdinosaurs=getDinosaurs()//Returns a promisedinosaurs.then(cacheDinosaurs)dinosaurs.then(renderDinosaurList)dinosaurs.then(renderDinosaursCount)
// This is how JQuery's $.ready() worksconstdomReady=()=>{constreadyState=document.readyStatereturnreadyState==="interactive"||readyState==="complete"
? Promise.resolve()
: newPromise((resolve)=>document.addEventListener("DOMContentLoaded",resolve))}constroar=()=>console.log("Roar!!!")constattachRoarHandler=()=>document.querySelector("button").addEventListener("click",roar);domReady()// Promise only resolves when the DOM is loaded.then(attachRoarHandler)
Can be coupled with fanning to great effect
Caching
Store a Promise into a cache instead of the values
This way, a hundred different things can request a remote resource and it will only hit it once
It does this by storing an unfulfilled Promise
Synchronous values don't populate the cache until the request finished causing all of the requests that come in before the request resolves will also try and hit the external resource
Throttling
Return the same Promise when something is asked for until it resolves
letthrottledPromiseconstresetThrottle=()=>throttledPromise=undefinedconstgetDinosaurs=()=>throttledPromise
? throttledPromise
: throttledPromise=Promise.resolve({name}).always(resetThrottle)constdinosaurs=getDinosaurs()console.log(dinosaurs===getDinosaurs())//-> truesetTimeout(()=>{//By now, the Promise has settled and is no longer pendingconsole.log(dinosaurs===getDinosaurs())//-> false})
This keeps data fresh, but prevents parallel requests for the same thing
All parallel requests get the same Promise back until it resolves and a new Promise is made
Fastest Promise
Promise.race offers a method to put a time-limit on how long an asynchronous task can take
letcache='[]'constretrieveDinosaurs=()=>//Don't resolve until 5 seconds have passednewPromise((resolve)=>setTimeout(()=>resolve(["Brontosaurus"]),2000))constgetCachedDinosaurs=()=>//Don't resolve until 2 seconds have passednewPromise((resolve)=>setTimeout(()=>resolve(getDinosaursFromCache()),1000))constsaveDinosaursToCache=(dinosaurs)=>cache=JSON.stringify(dinosaurs)constgetDinosaursFromCache=()=>JSON.parse(cache)constgetDinosaurs=()=>retrieveDinosaurs().tap(saveDinosaursToCache)constlog=(value)=>console.log(value)Promise.race([getDinosaurs(),getCachedDinosaurs()]).tap(log)setTimeout(()=>Promise.race([getDinosaurs(),getCachedDinosaurs()]).tap(log),3000)
If a connection is unreliable, take data from the cache and update the cache later
WIP Multiple Dependencies
WIP Promise Map
WIP Promise Reduce
WIP Promise Filter
async/await
The future syntax of Promise
asyncfunctiongetDinosaurs(){constdinosaurs=awaitapi.dinosaurs.get()//returns a Promiseconstnames=dinosaurs.map((dinosaur)=>dinosaur.name)returnnames}