Home > Article > Web Front-end > Detailed explanation of Promise usage in JavaScript_Basic knowledge
Many languages, in order to handle asynchronous patterns more like normal sequences, include a library of interesting solutions, called promises, deferreds, or futures. JavaScript promises can promote separation of concerns in place of tightly coupled interfaces. This article talks about JavaScript promises based on the Promises/A standard. [http://wiki.commonjs.org/wiki/Promises/A]
Promise use cases:
JavaScript promise is an object that promises to return a value in the future. Is a data object with well-defined behavior. A promise has three possible states:
A promise that has been rejected or completed is considered resolved. A promise can only move from pending to resolved. After that, the state of the promise is unchanged. A promise can exist long after its corresponding processing has completed. In other words, we can obtain the processing results multiple times. We get the result by calling promise.then(). This function will not return until the processing corresponding to the promise is completed. We can flexibly string together a bunch of promises. These concatenated "then" functions should return a new promise or the earliest one.
With this style, we can write asynchronous code just like we write synchronous code. Mainly achieved by combining promises:
Why bother? Can't we just use the basic callback function?
Problem with callback function
Callback functions are suitable for simple recurring events, such as validating a form based on a click, or saving the results of a REST call. Callback functions also create a chain of code, with one callback function calling a REST function, setting up a new callback function for the REST function, and this new callback function calling another REST function, and so on. The horizontal growth of code is greater than the vertical growth. The callback function seems simple, until we need a result, and we need it immediately, immediately for use in the calculation of the next line.
'use strict'; var i = 0; function log(data) {console.log('%d %s', ++i, data); }; function validate() { log("Wait for it ..."); // Sequence of four Long-running async activities setTimeout(function () { log('result first'); setTimeout(function () { log('result second'); setTimeout(function () { log('result third'); setTimeout(function () { log('result fourth') }, 1000); }, 1000); }, 1000); }, 1000); }; validate();
I use timeout to simulate asynchronous operations. The method of managing exceptions is painful and can easily exploit downstream behavior. When we write callbacks, then the code organization becomes confusing. Figure 2 shows a mock validation flow that can be run on the NodeJS REPL. In the next section, we will move from the pyramid-of-doom pattern to a continuous promise.
Figure
'use strict'; var i = 0; function log(data) {console.log('%d %s', ++i, data); }; // Asynchronous fn executes a callback result fn function async(arg, callBack) { setTimeout(function(){ log('result ' + arg); callBack(); }, 1000); }; function validate() { log("Wait for it ..."); // Sequence of four Long-running async activities async('first', function () { async('second',function () { async('third', function () { async('fourth', function () {}); }); }); }); }; validate();
Results of execution in NodeJS REPL
$ node scripts/examp2b.js 1 Wait for it ... 2 result first 3 result second 4 result third 5 result fourth $
I once encountered a situation where AngularJS dynamic validation dynamically limited the value of the form item based on the value of the corresponding table. The valid value range of the limit item is defined on the REST service.
I wrote a scheduler to operate the function stack according to the requested value to avoid callback nesting. The scheduler pops the function from the stack and executes it. The function's callback will call the scheduler again at the end until the stack is cleared. Each callback logs all validation errors returned from the remote validation call.
I think what I wrote is an anti-pattern. If I use the promise provided by Angular's $http call, my thinking during the entire verification process will be more linear, like synchronous programming. Flattened promise chains are readable. Continue...
Use Promises
The kew promise library is used. The same applies to the Q library. To use the library, first import the kew library into NodeJS using npm, then load the code into the NodeJS REPL.
Figure
'use strict'; var Q = require('kew'); var i = 0; function log(data) {console.log('%d %s', ++i, data); }; // Asynchronous fn returns a promise function async(arg) { var deferred = Q.defer(); setTimeout(function () { deferred.resolve('result ' + arg);\ }, 1000); return deferred.promise; }; // Flattened promise chain function validate() { log("Wait for it ..."); async('first').then(function(resp){ log(resp); return async('second'); }) .then(function(resp){ log(resp); return async('third') }) .then(function(resp){ log(resp); return async('fourth'); }) .then(function(resp){ log(resp); }).fail(log); }; validate();
The output is the same as when using nested callbacks:
$ node scripts/examp2-pflat.js 1 Wait for it ... 2 result first 3 result second 4 result third 5 result fourth $
该代码稍微“长高”了,但我认为更易于理解和修改。更易于加上适当的错误处理。在链的末尾调用fail用于捕获链中错误,但我也可以在任何一个then里面提供一个reject的处理函数做相应的处理。
服务器 或 浏览器
Promises在浏览器中就像在NodeJS服务器中一样有效。下面的地址, http://jsfiddle.net/mauget/DnQDx/,指向JSFiddle的一个展示如何使用一个promise的web页面。 JSFiddle所有的代码是可修改的。我故意操作随意动作。你可以试几次得到相反的结果。它是可以直接扩展到多个promise链, 就像前面NodeJS例子。
并行 Promises
考虑一个异步操作喂养另一个异步操作。让后者包括三个并行异步行为,反过来,喂最后一个行动。只有当所有平行的子请求通过才能通过。这是灵感来自偶遇一打MongoDB操作。有些是合格的并行操作。我实现了promises的流流程图。
我们怎么会模拟那些在该图中心行的并行promises?关键是,最大的promise库有一个全功能,它产生一个包含一组子promises的父promie。当所有的子promises通过,父promise通过。如果有一个子promise拒绝,父promise拒绝。
让十个并行的promises每个都包含一个文字promise。只有当十个子类通过或如果任何子类拒绝,最后的then方法才能完成。
Figure
var promiseVals = ['To ', 'be, ', 'or ', 'not ', 'to ', 'be, ', 'that ', 'is ', 'the ', 'question.']; var startParallelActions = function (){ var promises = []; // Make an asynchronous action from each literal promiseVals.forEach(function(value){ promises.push(makeAPromise(value)); }); // Consolidate all promises into a promise of promises return Q.all(promises); }; startParallelActions ().then( . . .
下面的地址, http://jsfiddle.net/mauget/XKCy2/,针对JSFiddle在浏览器中运行十个并行promises,随机的拒绝或通过。这里有完整的代码用于检查和变化if条件。重新运行,直到你得到一个相反的完成。
孕育 Promise
许多api返回的promise都有一个then函数——他们是thenable。通常我只是通过then处理thenable函数的结果。然而,$q,mpromise,和kew库拥有同样的API用于创建,拒绝,或者通过promise。这里有API文档链接到每个库的引用部分。我通常不需要构造一个promise,除了本文中的包装promise的未知描述和timeout函数。请参考哪些我创建的promises。
Promise库互操作
大多数JavaScript promise库在then级别进行互操作。你可以从一个外部的promise创建一个promise,因为promise可以包装任何类型的值。then可以支持跨库工作。除了then,其他的promise函数则可能不同。如果你需要一个你的库不包含的函数,你可以将一个基于你的库的promise包装到一个新的,基于含有你所需函数的库创建的promise里面。例如,JQuery的promise有时为人所诟病。那么你可以将其包装到Q,$q,mpromise,或者kew库的promise中进行操作。
结语
现在我写了这篇文章,而一年前我却是犹豫要不要拥抱promise的那个。我只是单纯地想完成一项工作。 我不想学习新的API,或是打破我原来的代码(因为误解了promise)。我曾经如此错误地认为!当我下了一点注时,就轻易就赢得了可喜的成果。
在这篇文章中,我已经简单给出了一个单一的promise,promise链,和一个并行的promise的promise的的例子。 Promises不难使用。如果我可以使用它们,任何人都可以。 要查看完整的概念,我支持你点击专家写的参考指南。从Promises/A 的参考开始,从事实上的标准JavaScript的Promise 开始。