2

I would like to know how js promises work internally.

I've googled but I couldn't find the answer (or I didn't know how to google).

I don't know how it gets back to you.

Lets say I have this client code:

function whatever() {
    doSomethingLocally;

    callPromiseThatGoesAllOverTheWorldAndThenGetsBackToYou()
        .then(
            doSomethingLocallyAgain
        );

     doSomeOtherThingLocally;
}

I would like to know how, when the promise is fulfilled, it gets back to the right point in code (that 'doSomethingLocallyAgain').

  • While the specification [describes how they _behave_](http://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects), how they actually _work internally_ are up to the remit of the implementer of the spec (ie the JavaScript engine). Is there an underlying reason you're asking about this, as perhaps that may be a better question? – James Thorpe Apr 29 '16 at 13:25
  • I'm asking this because I don't know how the flow goes back to that exactly point. I don't know if there is a socket that keeps listening to something with a pointer so when it receives the response it changes the flow to that exactly point. – Bruno Feroleto Apr 29 '16 at 13:35
  • `doSomethingLocallyAgain` has to be a function. You are passing that function to the promise and it simply calls that function once it's done. There is nothing magical about it. Here is simplified example of how callbacks work: `function do(f) { setTimeout(() => { /* do some internal stuff */ f(); }, 3000); }; do(() => console.log('call me maybe'));`. In this example, `do` accepts a function and calls it when it's ready. – Felix Kling Apr 29 '16 at 13:39
  • If you are not strictly interested in engine internals (of the native ES6 implementations), you might be interested in [Concept - Distilling how a promise works?](http://stackoverflow.com/q/15668075/1048572) or [How is a promise/defer library implemented?](http://stackoverflow.com/q/17718673/1048572) – Bergi Apr 29 '16 at 13:47
  • Yeah, that helps a lot, @Bergi. I'll also add this: https://www.promisejs.org/implementing/ I was thinking something like you call an promises that goes to an api to get the result you want and than comes back to you and also how could I make it become synchronous to my code. – Bruno Feroleto Apr 29 '16 at 14:17
  • I, too, have this same question. Is the browser JavaScript code available for the Promise class? – David Spector May 27 '21 at 20:39

1 Answers1

3

A promise is just a fancy return value you can attach callbacks to, instead of passing them to the function. Add the nice invariant that the callbacks are never called immediately, but always put on a micro-task queue, and that's pretty much it.

jib
  • 40,579
  • 17
  • 100
  • 158