alright so the key thing to grasp first is the difference between sync and async operations.
imagine you’re browsing a photo gallery website that shows cat pictures. when you search for cats, the site needs to display “loaded 150 photos in 2.3 seconds” at the top. let’s call this display message task X.
but task X can only show up after all 150 cat photos are actually downloaded from the server. the downloading happens first obviously. let’s call this downloading process task Y.
normally these would run one after another (synchronously). task Y takes forever because of things like slow internet, busy servers, the website’s algorithm finding the right cat images. task X is super fast since it’s just showing text, but it has to wait for the slow task Y to finish.
task Y
[slow work: download cat photos] -------→ (then) task X(show “150 photos loaded in 2.3 seconds”)
meanwhile, we can still load the basic html,css layout of the photo gallery without making users stare at a blank screen for 2.3 seconds. loading the html,css structure is quick but can happen at the same time (asynchronously) to give users something to look at. the website basically says “hey, images are still loading but here’s the page layout so you don’t think we crashed”. let’s call this task Z. so while task Y → task X runs, we don’t freeze everything and can run the faster task Z in parallel.
now let’s add the coding terms to make this look like real javascript. since task X should only run when task Y finishes, we wrap task Y in a promise and attach task X as a callback
promiseoftasky.then(callbacktaskx) or simpler
downloadphotos.then(displaytext *150 photos loaded in 2.3 seconds*);
then we write task Z code after this. task Z isn’t part of the promise chain.
when learning promises, we usually start with setTimeout examples because real examples can be overwhelming at first.
to demo task Y (the slow process), we use a timer that simulates something taking time.
function createDelayPromise() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("your data is ready");
}, 3000);
});
}
createDelayPromise().then((result) => {
console.log(result);
});