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:
functionrun_then_promise(){// our rudimentary custom promiseletpromise={}// a `then` method to set the success callbackpromise.then=(callback)=>{promise.resolve=callback}// a default callback in case `then` is never usedpromise.resolve=()=>console.log("Nothing happens...")// call the function, with a callback that defers to the promiserun_then_callback(()=>promise.resolve())// return the promise to the callerreturnpromise}
Now we can call this function and it will already look a surprising lot like JavaScripts promises.
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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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:Now we can call this function and it will already look a surprising lot like JavaScripts promises.
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.