The Mystery of Promise Function then in JavaScript

Overview of Promise

  • Promise object is a specification proposed by CommonJS working group, which aims to provide a unified interface for asynchronous operation.

So what is Promises?

First, it is an object, that is to say, no different from the use of other JavaScript objects; secondly, it acts as proxy and mediates between asynchronous operations and callback functions. It makes the asynchronous operation have the interface of synchronous operation, makes the program have the normal process of synchronous operation, callback functions need not be nested layer by layer.

Simply put, the idea is that each asynchronous task immediately returns a Promise object, and since it returns immediately, the process of synchronous operation can be adopted. This Promises object has a then method that allows you to specify callback functions that are called after the asynchronous task is completed.

Promise's then method can accept the execution result of the previous function and guarantee the sequential execution of another Promise. How on earth can this be achieved?

Schematic diagram (above)

Problem demand

How to ensure that multiple promise s are executed sequentially?

Example:

var f1 = function (){
 return new Promise(function (resolve, reject){
  setTimeout(function (){
   console.log("f1 ok!")
   resolve("f1 ok!");
  }, 1000)
 });
}
var f2 = function (){
 return new Promise(function (resolve, reject){
  setTimeout(function (){
   console.log("f2 ok!")
   resolve("f2 ok!");
  }, 3000)
 });
}
var f3 = function (){
 return new Promise(function (resolve, reject){
  setTimeout(function (){
   console.log("f3 ok!")
   resolve("f3 ok!");
  }, 2000)
 });
}
//Front-end stack learning exchange circle: 866109386
//For 1-3 Experience Front End Developers
//Help break through technical bottlenecks and enhance thinking ability

Of course, if we want to be parallel, we can easily think of the Promise.all method:

Promise.all([f1(), f2(), f3()]).then(function (data){
 console.log(data)
})
// f1 ok! 
// f3 ok! 
// f2 ok! 
// ["f1 ok!", "f2 ok!", "f3 ok!"]

If it is to be executed sequentially:

f1().then(f2).then(f3)
// f1 ok!
// f2 ok!
// f3 ok!
 
//Or so
 
function f(all) {
 var promise = Promise.resolve();
 all.forEach((p, index) => {
  promise = promise.then(p)
 })
}
f([f1, f2, f3])

So the question arises, how can the then be executed sequentially? A parameter can be either a normal function or a function that returns promise?

The Mystery of the N

Many libraries that implement promises are complex. If you implement promises yourself, you can learn from the following simple code:

Promise.prototype.then = function(onFulfilled, onRejected) {
 var promise = this;
 return new Promise(function(resolve, reject) {
  function handle(value) {
   var ret = typeof onFulfilled === 'function' && onFulfilled(value) || value;
   if (ret && typeof ret['then'] == 'function') {
    ret.then(function(value) {
     resolve(value);
    }, function(reason) {
     reject(reason);
    });
   } else {
    resolve(ret);
   }
  }
  function errback(reason) {
   reason = typeof onRejected === 'function' && onRejected(reason) || reason;
   reject(reason);
  }
  if (promise._status === 'PENDING') {
   promise._resolves.push(handle);
   promise._rejects.push(errback);
  } else if (promise._status === FULFILLED) { 
   callback(promise._value);
  } else if (promise._status === REJECTED) {
   errback(promise._reason);
  }
 });
}
//Front-end stack learning exchange circle: 866109386
//For 1-3 Experience Front End Developers
//Help break through technical bottlenecks and enhance thinking ability

Focus on the implementation of the then. Look at the code above. What each then returns is a new Promise, a new Promise, a new Promise.

The second point is that the result of a callback function running is a promise judgment internally. If you wait for the promise to run before calling the resolve to change the state, the key is the timing of the resolve call, the timing of the resolve call, to be able to execute further. These two steps are the key of the then function.

Is it a little dizzy? Look at the first picture.

Keywords: Front-end Javascript

Added by bob2006 on Fri, 17 May 2019 16:31:02 +0300