DEV Community

Discussion on: How I learned to avoid implied globals (and why)

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

The easiest way to understand promises might be to just implement them:

Let's say we have a function run_then_callback(callback), which does some work asynchronously and then calls its callback. We could wrap this function like this:

function run_then_promise() {
   // our rudimentary custom promise
   let promise = {}

   // a `then` method to set the success callback
   promise.then = (callback) => { promise.resolve = callback }

   // a default callback in case `then` is never used
   promise.resolve = () => console.log("Nothing happens...")

   // call the function, with a callback that defers to the promise
   run_then_callback( () => promise.resolve() )

   // return the promise to the caller
   return promise
}
Enter fullscreen mode Exit fullscreen mode

Now we can call this function and it will already look a surprising lot like JavaScripts promises.

run_then_promise().then( () => console.log("Something happens!") )
Enter fullscreen mode Exit fullscreen mode

From there, there's some obvious refactoring to be done, like creating an actual promise class and move most of this logic in there.

That's really all there is to the core idea; everything else is just fluff, like being able to chain promises and stuff. Of course, they also have extra logic for when a callback returns a new promise, for error handling, etc. But none of that really changes the principle.