1

I'm trying to figure out how promises are handled in the runtime environment. Are they moved into the web API container until they resolve and then pushed into the callstack when .then is called? Here is some example code. Console.log runs before the promises which leads me to believe somewhere along the way they end up in the queue. I also noticed I can put a function in a .then and the returned promise will fill that functions parameters.

// asynchronous test
let promiseWhatever = new Promise( function(resolve, reject){

 // variable to be chained later and passed in function argument
  let chainedVariable = 'I am chained';
  resolve(chainedVariable);
  reject('rejected promise');
});

let promiseMe = function(promiseResult) {
  let message = `${promiseResult} to my computer`;
  return Promise.resolve(message); 
  // resolves here to be passed onto the second chained then
};


function hello() {


  promiseWhatever
  .then(promiseMe) 
  // how does promiseMe take in the result for its argument?

  // then returns another promise and you can chain them
  .then( function(fulfilled){
    console.log(fulfilled);
  }) // is fullfilling the code to display the string to the console.
  .catch( function(err) {
    console.log(err);
  });

  console.log('hello'); // logs first to the console

};

hello();
larry burns
  • 189
  • 1
  • 9
  • 1
    Possible duplicate of [How do promises work in JavaScript?](https://stackoverflow.com/questions/18422021/how-do-promises-work-in-javascript) – Dan O Jun 15 '19 at 19:25
  • there are many, many, MANY questions on Stack Overflow regarding how Javascript promises work. Which of them have you researched, and what specific questions did they not answer? – Dan O Jun 15 '19 at 19:26
  • None of them answered how promises are handled in the runtime environment, which is my question. – larry burns Jun 16 '19 at 14:07
  • You might be interested in my answer [here](https://stackoverflow.com/a/61464197/38522). – Ben Aston Apr 28 '20 at 11:24

1 Answers1

3

First off a promise is just a notification scheme. The underlying asynchronous operation (whatever code resolves or rejects the promise) that would typically be outside of Javascript (using native code) such as an incoming webSocket message or an ajax response or something like that.

All promise engines use the event queue. When a promise is resolved, they post an event to the event queue in order to trigger the appropriate .then() or .catch() handler to be called. It is not required by the language or promise specification, but a number of implementations use a special event queue for promise callbacks that is checked along with other types of event queues.

It is required by the promise specification that a .then() or .catch() handler is always called asynchronously AFTER the current event loop code has finished even if the promise is resolved immediately. That's why your console.log('hello') shows before the console.log() inside the .then() handler. This is by design and is done in order to create consistency on when a promise calls it's handlers (always after the current event loop code completes).

Are they moved into the web API container until they resolve and then pushed into the callstack when .then is called?

When a promise is resolved an event is inserted into the event queue which will cause the appropriate .then() callbacks to get called after the current event loop code has completed (on a future event loop cycle).

It's not clear what you mean by "web API container" so I can't comment on that.

I also noticed I can put a function in a .then and the returned promise will fill that functions parameters

Yes, this is how promises work. A .then() handler is passed a single argument that represents the resolved value of the promise. A .catch() handler is passed a single argument that represents the reject reason.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • So the promise is handled like an event and sent to the web API container until it's resolved. The value is then sent to the queue and once the call stack is clear inserts the value into the .then or .catch method? Here's what I mean by web API container https://medium.com/@olinations/the-javascript-runtime-environment-d58fa2e60dd0 – larry burns Jun 16 '19 at 14:46
  • @larryburns - A resolved promise inserts an event into the event queue. When the event loop decides that it is time to execute that event, it triggers that event which grabs the resolved value from the promise and passes it to the `.then()` handler callback and calls that callback. "web container" is not a standard way of describing anything in the Javascript engine. In the diagram in that article, "web APIs" look like they are native code that works asynchronously and uses the event queue (such as timers, ajax calls, etc...). – jfriend00 Jun 16 '19 at 15:23
  • So when the code reaches the promise object it inserts it directly into the queue? Once the callstack is empty the event is triggered and the promise is inserted into the .then callback? Is that what you mean by "once the current event loop code has completed"? – larry burns Jun 16 '19 at 16:15
  • @larryburns - When the promise completes, it inserts an event in the event queue. When that event gets its turn to run, then the promise calls it `.then()` handler and passes the resolved value to it. Nothing is inserted into the event queue on behalf of the promise until the promise is resolved or rejected. – jfriend00 Jun 16 '19 at 16:37
  • @larryburns - If this answered your question, you can indicate that to the community here at stackoverflow by clicking the checkmark to the left of the answer to "accept" this answer. That will also earn you some reputation points on stackoverflow for following the proper procedure. – jfriend00 Jun 22 '19 at 00:39