C
C
cybervito212015-10-09 19:58:49
JavaScript
cybervito21, 2015-10-09 19:58:49

How does chaining work in the simplest implementation of Promise in Javascript?

I did a review of a simple implementation of promises in JS .
I came across this line

this._timeout = setTimeout(this._processQueue.bind(this), 0);

I suspect there is some magic in it.
And an example:
var a = new Promise(
  function(resolve, reject) {
    setTimeout(function() {
      resolve('some_data');
    }, 1500);
  }).then(function() {
    setTimeout(function() {
      console.log('yep');
    }, 1500);
  }).then(function () {
    console.log('ok');
  });

Like console.log('ok'); waiting for it to work
setTimeout(function() {
        console.log('yep');
      }, 1500);

How does setTimeout( ) itself resolve in .then( ) ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
namitos, 2015-10-10
@cybervito21

>Like console.log('ok'); waits for it to work
and does not wait. first ok, then yep
>How does setTimeout() resolve itself in .then()?
it does not resolve in any way :)
everything is simpler than it seems. until a promise is returned in then, the next then will be executed.
if you are where console.log('yep') is, you will return a promise and resolve it by timeout, then the chain will be executed in order.
it is possible that you are using some kind of crooked implementation of promises. try native in node or chrome, or see how it's done in vow or bluebird

A
Alexey P, 2015-10-09
@ruddy22

everything is not difficult. Like...
Regarding the first piece of code.
Apparently, in your implementation, this line implements the binding of the window timer to the property of the object, which is then used somewhere.
And the second piece of code does this:
- we get the promise instance to which we passed the callback executor.
- the callback receives 2 methods during execution, the first returns data to saxes, the second - to fail
- then, the timer expires and returns data to .then, in which the suxes function is declared
- then it is executed (function)
- the data is passed further to then
- each object returns a promise

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question