Home > Article > Web Front-end > Detailed interpretation of the use of Promise in JavaScript programming_Basic knowledge
Promise core description
Although Promise already has its own specifications, the current various Promise libraries have differences in the implementation details of Promise, and some APIs are even completely different in meaning. But the core content of Promise is the same, it is the then method. In related terms, a promise refers to an object or function that has a then method that can trigger specific behavior.
Promise can be implemented in different ways, so the Promise core description does not discuss any specific implementation code.
Read the core description of Promise first. It means: Look, this is the result that needs to be written. Please refer to this result to think about how to write it in code.
Getting Started: Understand Promise in this way
Recall what problem Promise solves? callback. For example, the function doMission1() represents the first thing. Now, we want to do the next thing doMission2() after this thing is completed. What should we do?
Let’s take a look at our common callback patterns first. doMission1() said: "If you want to do this, give me doMission2() and I will call it for you after it is finished." So it will be:
doMission1(doMission2);
What about Promise mode? You said to doMission1(): "No, the control is with me. You should change it. You return a special thing to me first, and then I will use this thing to arrange the next thing." This special thing is Promise, this will look like this:
doMission1().then(doMission2);
It can be seen that Promise changes the master-slave relationship of the callback mode (turn over and become the master!). The process relationship of multiple events can be concentrated on the main road (instead of being scattered among various event functions). Inside).
Okay, how to do such a conversion? Let's start with the simplest case, assuming that the code of doMission1() is:
function doMission1(callback){ var value = 1; callback(value); }
Then, it can be changed to look like this:
function doMission1(){ return { then: function(callback){ var value = 1; callback(value); } }; }
This completes the conversion. Although it is not an actually useful conversion, here we have actually touched on the most important implementation point of Promise, that is, Promise converts the return value into an object with a then method.
Advanced: Q’s design journey
Start from defer
design/q0.js is the first step in the initial shaping of Q. It creates a utility function called defer for creating Promise:
var defer = function () { var pending = [], value; return { resolve: function (_value) { value = _value; for (var i = 0, ii = pending.length; i < ii; i++) { var callback = pending[i]; callback(value); } pending = undefined; }, then: function (callback) { if (pending) { pending.push(callback); } else { callback(value); } } } };
As can be seen from this source code, running defer() will get an object, which contains two methods: resolve and then. Please recall jQuery's Deferred (also resolve and then), these two methods will have similar effects. Then will refer to the pending status, and if it is in the waiting state, the callback will be saved (push), otherwise the callback will be called immediately. resolve will affirm the Promise, update the value and run all saved callbacks at the same time. Examples of defer usage are as follows:
var oneOneSecondLater = function () { var result = defer(); setTimeout(function () { result.resolve(1); }, 1000); return result; };
oneOneSecondLater().then(callback);
Here oneOneSecondLater() contains asynchronous content (setTimeout), but here it immediately returns an object generated by defer(), and then calls the object's resolve method at the end of the asynchronous end (with the upper value, or in other words result).
At this point, there is a problem with the above code: resolve can be executed multiple times. Therefore, the judgment of the status should be added to the resolve to ensure that the resolve is only valid once. This is the design/q1.js of Q next step (only the difference part):
resolve: function (_value) { if (pending) { value = _value; for (var i = 0, ii = pending.length; i < ii; i++) { var callback = pending[i]; callback(value); } pending = undefined; } else { throw new Error("A promise can only be resolved once."); } }
For the second and subsequent calls, you can throw an error like this, or you can just ignore it.
Separate defer and promise
In the previous implementation, the object generated by defer has both the then method and the resolve method. By definition, promise cares about the then method. As for the resolve that triggers the promise to change the state, it is another matter. Therefore, Q will next separate the promise with the then method and the defer with resolve, and use each independently. This is like clarifying their respective responsibilities and leaving only certain permissions. This will make the code logic clearer and easier to adjust. Please see design/q3.js: (q2 is skipped here)
var isPromise = function (value) { return value && typeof value.then === "function"; }; var defer = function () { var pending = [], value; return { resolve: function (_value) { if (pending) { value = _value; for (var i = 0, ii = pending.length; i < ii; i++) { var callback = pending[i]; callback(value); } pending = undefined; } }, promise: { then: function (callback) { if (pending) { pending.push(callback); } else { callback(value); } } } }; };
If you compare q1 carefully, you will find that the difference is very small. On the one hand, the error is no longer thrown (instead of directly ignoring the second and more resolves), on the other hand, the then method is moved to an object named promise. At this point, the object obtained by running defer() (let's call it defer) will have a resolve method and a promise attribute pointing to another object. This other object is a promise with only a then method. This completes the separation.
There is also an isPromise() function in front, which determines whether the object is a promise by whether it has a then method (duck-typing judgment method). In order to correctly use and handle detached promises, you need to distinguish promises from other values like this.
Implementing promise cascade
The next step will be quite important. Up until q3, the promises implemented cannot be cascaded. But the promises you are familiar with should support syntax like this:
promise.then(step1).then(step2);
以上过程可以理解为,promise将可以创造新的promise,且取自旧的promise的值(前面代码中的value)。要实现then的级联,需要做到一些事情:
design/q4.js中,为了实现这一点,新增了一个工具函数ref:
var ref = function (value) { if (value && typeof value.then === "function") return value; return { then: function (callback) { return ref(callback(value)); } }; };
这是在着手处理与promise关联的value。这个工具函数将对任一个value值做一次包装,如果是一个promise,则什么也不做,如果不是promise,则将它包装成一个promise。注意这里有一个递归,它确保包装成的promise可以使用then方法级联。为了帮助理解它,下面是一个使用的例子:
ref("step1").then(function(value){ console.log(value); // "step1" return 15; }).then(function(value){ console.log(value); // 15 });
你可以看到value是怎样传递的,promise级联需要做到的也是如此。
design/q4.js通过结合使用这个ref函数,将原来的defer转变为可级联的形式:
var defer = function () { var pending = [], value; return { resolve: function (_value) { if (pending) { value = ref(_value); // values wrapped in a promise for (var i = 0, ii = pending.length; i < ii; i++) { var callback = pending[i]; value.then(callback); // then called instead } pending = undefined; } }, promise: { then: function (_callback) { var result = defer(); // callback is wrapped so that its return // value is captured and used to resolve the promise // that "then" returns var callback = function (value) { result.resolve(_callback(value)); }; if (pending) { pending.push(callback); } else { value.then(callback); } return result.promise; } } }; };
原来callback(value)的形式,都修改为value.then(callback)。这个修改后效果其实和原来相同,只是因为value变成了promise包装的类型,会需要这样调用。
then方法有了较多变动,会先新生成一个defer,并在结尾处返回这个defer的promise。请注意,callback不再是直接取用传递给then的那个,而是在此基础之上增加一层,并把新生成的defer的resolve方法放置在此。此处可以理解为,then方法将返回一个新生成的promise,因此需要把promise的resolve也预留好,在旧的promise的resolve运行后,新的promise的resolve也会随之运行。这样才能像管道一样,让事件按照then连接的内容,一层一层传递下去。
加入错误处理
promise的then方法应该可以包含两个参数,分别是肯定和否定状态的处理函数(onFulfilled与onRejected)。前面我们实现的promise还只能转变为肯定状态,所以,接下来应该加入否定状态部分。
请注意,promise的then方法的两个参数,都是可选参数。design/q6.js(q5也跳过)加入了工具函数reject来帮助实现promise的否定状态:
var reject = function (reason) { return { then: function (callback, errback) { return ref(errback(reason)); } }; };
它和ref的主要区别是,它返回的对象的then方法,只会取第二个参数的errback来运行。design/q6.js的其余部分是:
var defer = function () { var pending = [], value; return { resolve: function (_value) { if (pending) { value = ref(_value); for (var i = 0, ii = pending.length; i < ii; i++) { value.then.apply(value, pending[i]); } pending = undefined; } }, promise: { then: function (_callback, _errback) { var result = defer(); // provide default callbacks and errbacks _callback = _callback || function (value) { // by default, forward fulfillment return value; }; _errback = _errback || function (reason) { // by default, forward rejection return reject(reason); }; var callback = function (value) { result.resolve(_callback(value)); }; var errback = function (reason) { result.resolve(_errback(reason)); }; if (pending) { pending.push([callback, errback]); } else { value.then(callback, errback); } return result.promise; } } }; };
这里的主要改动是,将数组pending只保存单个回调的形式,改为同时保存肯定和否定的两种回调的形式。而且,在then中定义了默认的肯定和否定回调,使得then方法满足了promise的2个可选参数的要求。
你也许注意到defer中还是只有一个resolve方法,而没有类似jQuery的reject。那么,错误处理要如何触发呢?请看这个例子:
var defer1 = defer(), promise1 = defer1.promise; promise1.then(function(value){ console.log("1: value = ", value); return reject("error happens"); }).then(function(value){ console.log("2: value = ", value); }).then(null, function(reason){ console.log("3: reason = ", reason); }); defer1.resolve(10); // Result: // 1: value = 10 // 3: reason = error happens
可以看出,每一个传递给then方法的返回值是很重要的,它将决定下一个then方法的调用结果。而如果像上面这样返回工具函数reject生成的对象,就会触发错误处理。
融入异步
终于到了最后的design/q7.js。直到前面的q6,还存在一个问题,就是then方法运行的时候,可能是同步的,也可能是异步的,这取决于传递给then的函数(例如直接返回一个值,就是同步,返回一个其他的promise,就可以是异步)。这种不确定性可能带来潜在的问题。因此,Q的后面这一步,是确保将所有then转变为异步。
design/q7.js定义了另一个工具函数enqueue:
var enqueue = function (callback) { //process.nextTick(callback); // NodeJS setTimeout(callback, 1); // Na?ve browser solution };
显然,这个工具函数会将任意函数推迟到下一个事件队列运行。
design/q7.js其他的修改点是(只显示修改部分):
var ref = function (value) { // ... return { then: function (callback) { var result = defer(); // XXX enqueue(function () { result.resolve(callback(value)); }); return result.promise; } }; }; var reject = function (reason) { return { then: function (callback, errback) { var result = defer(); // XXX enqueue(function () { result.resolve(errback(reason)); }); return result.promise; } }; }; var defer = function () { var pending = [], value; return { resolve: function (_value) { // ... enqueue(function () { value.then.apply(value, pending[i]); }); // ... }, promise: { then: function (_callback, _errback) { // ... enqueue(function () { value.then(callback, errback); }); // ... } } }; };
即把原来的value.then的部分,都转变为异步。
到此,Q提供的Promise设计原理q0~q7,全部结束。
结语
即便本文已经是这么长的篇幅,但所讲述的也只到基础的Promise。大部分Promise库会有更多的API来应对更多和Promise有关的需求,例如all()、spread(),不过,读到这里,你已经了解了实现Promise的核心理念,这一定对你今后应用Promise有所帮助。
在我看来,Promise是精巧的设计,我花了相当一些时间才差不多理解它。Q作为一个典型Promise库,在思路上走得很明确。可以感受到,再复杂的库也是先从基本的要点开始的,如果我们自己要做类似的事,也应该保持这样的心态一点一点进步。