Organizing asynchronous code with ES6 +promise

Source: Internet
Author: User

(1) Why use this design pattern of promise, what are the benefits of this design pattern?

The traditional way to solve a JavaScript asynchronous event is to call a callback function, invoke a method, then give it a function reference, and execute the function reference when the method ends.

Artifact from Javascript--promisepromise in JS

callback function The real problem is that he deprives us of the ability to use return and throw these keywords. And Promise a good solution to all this.

In June 2015, the official version of ECMAScript 6 was finally released.

ECMAScript is an international standard for JavaScript, and JavaScript is the implementation of ECMAScript. The goal of ES6 is to make JavaScript languages available for writing large, complex applications that become enterprise-level development languages.

Concept

ES6 Native provides the Promise object.

The so-called Promise is an object that is used to pass the message of an asynchronous operation. It represents an event in the future that will know the result (usually an asynchronous operation), and this event provides a unified API for further processing.

The Promise object has the following two characteristics.

(1) The state of the object is unaffected by the outside world. The Promise object represents an asynchronous operation in three states: Pending (in progress), resolved (completed, also known as fulfilled), and rejected (failed). Only the result of an asynchronous operation can determine which state is currently, and no other operation will change that state. This is also the origin of the name Promise, its English meaning is "commitment", that other means can not be changed.

(2) Once the state changes, it will not change, and can get this result at any time. There are only two possible changes to the state of the Promise object: from Pending to resolved and from Pending to rejected. As long as these two situations occur, the state is solidified and will not change, and will keep the result. Even if the change has occurred, you can add a callback function to the Promise object, and you will get the result immediately. This is quite different from the event, which is characterized by the event that if you miss it and then listen to it, you won't get the result.

With the Promise object, the asynchronous operation can be expressed in the process of synchronous operation, avoiding the nested callback functions of layers. In addition, the Promise object provides a unified interface that makes it easier to control asynchronous operations.

Promise also has some drawbacks. First, the Promise cannot be canceled, and once it is newly created it executes immediately and cannot be canceled halfway. Second, if you do not set a callback function, the Promise inside throws an error and does not react externally. Third, when in the Pending state, it is not possible to know the current progress to which stage (just beginning or nearing completion).

var promise = new Promise(function(resolve, reject) { if (/* 异步操作成功 */){ resolve(value); } else { reject(error); }});promise.then(function(value) { // success}, function(value) { // failure});

The Promise constructor takes a function as a parameter, and the two parameters of the function are the Resolve method and the Reject method respectively.

If the asynchronous operation succeeds, the state of the Promise object is changed from "unfinished" to "succeeded" (that is, from pending to resolved) using the Resolve method;

If the asynchronous operation fails, The Reject method is used to change the state of the Promise object from "Unfinished" to "failed" (that is, from pending to rejected).

The basic API
    1. Promise.resolve ()
    2. Promise.reject ()
    3. Promise.prototype.then ()
    4. Promise.prototype.catch ()
    5. Promise.all ()//all completed

      var p = Promise.all([p1,p2,p3]);
    6. Promise.race ()//racing, complete one can
Advanced

The magic of promises is to give us the previous return and throw, and each Promise will provide a then () function, and a catch (), which is actually the then (null, ...) function,

    somePromise().then(functoin(){        // do something    });

We can do three things,

1. return 另一个 promise2. return 一个同步的值 (或者 undefined)3. throw 一个同步异常 ` throw new Eror(‘‘);`
1. Encapsulating synchronous and asynchronous code
```new Promise(function (resolve, reject) { resolve(someValue); });```写成```Promise.resolve(someValue);```
2. Capturing synchronization exceptions
new Promise(function (resolve, reject) { throw new Error(‘悲剧了,又出 bug 了‘); }).catch(function(err){ console.log(err); });

In the case of synchronous code, you can write

    Promise.reject(new Error("什么鬼"));
3. Multiple exception captures for more precise capture
Somepromise.then (function return a.b.c.d ();}). catch (TypeError, function< Span class= "Hljs-params" > (e) {//if A is defined, would end up here because //it is a type error to reference property of undefined}). catch (referenceerror,  Function (e) {//will end up here if a wasn ' t defined @ all}). catch (function  (e) {//generic catch-the rest, error wasn ' t TypeError nor //referenceerror})            
4. Get the return value of two Promise
1. .then 方式顺序调用2. 设定更高层的作用域3. spread
5. Finally
catch 之后
6. Bind
somethingAsync().bind({}).spread(function (aValue, bValue) { this.aValue = aValue; this.bValue = bValue; return somethingElseAsync(aValue, bValue);}).then(function (cValue) { return this.aValue + this.bValue + cValue;});

Or you can do it.

var scope = {};somethingAsync().spread(function (aValue, bValue) { scope.aValue = aValue; scope.bValue = bValue; return somethingElseAsync(aValue, bValue);}).then(function (cValue) { return scope.aValue + scope.bValue + cValue;});

However, there are very many differences,

    1. You must first declare that there is a risk of wasting resources and memory leaks
    2. cannot be used in the context of an expression
    3. Less efficient
7. All. is very useful for handling a Promise list 8 with a dynamic size uniformity. Join Ideal for handling multiple separate Promise
```var join = Promise.join;join(getPictures(), getComments(), getTweets(), function(pictures, comments, tweets) { console.log("in total: " + pictures.length + comments.length + tweets.length);});```
9. Props. Processes a promise Map collection. There is only one failure, and all execution is over.
```Promise.props({ pictures: getPictures(), comments: getComments(), tweets: getTweets()}).then(function(result) { console.log(result.tweets, result.pictures, result.comments);});```
Any, some, race
```Promise.some([ ping("ns1.example.com"), ping("ns2.example.com"), ping("ns3.example.com"), ping("ns4.example.com")], 2).spread(function(first, second) { console.log(first, second);}).catch(AggregateError, function(err) {

Err.foreach (function (e) {
Console.error (E.stack);
});
});;

```有可能,失败的 promise 比较多,导致,Promsie 永远不会 fulfilled
One: Map (Function mapper [, Object options])
用于处理一个数组,或者 promise 数组,

Option:concurrency and found

    map(..., {concurrency: 1});

The following are unlimited concurrent quantities, reading file information

VarPromise =Require"Bluebird");var join =Promise.join;var fs =Promise.promisifyall (Require"FS"));var concurrency =Parsefloat (process.argv[2] | |"Infinity");var fileNames = ["File1.json","File2.json"];Promise.map (FileNames,functionfileName) { return Fs.readfileasync (fileName). Then (json.parse). catch (SyntaxError, function (e) { E.filename = FileName; throw E;})}, {concurrency:concurrency}). Then (function (parsedjsons) { console.log (parsedjsons);}). catch (SyntaxError, function (e) { console.log ("Invalid JSON in File" + E.filename + ":" + E . message);});               

Results

$ sync && echo 3 > /proc/sys/vm/drop_caches$ node test.js 1reading files 35ms$ sync && echo 3 > /proc/sys/vm/drop_caches$ node test.js Infinityreading files: 9ms
One: Reduce (Function reducer [, Dynamic InitialValue]), Promise
promise.reduce ([" file1.txt ", " File2.txt ", " File3.txt "], function (total, fileName) {return fs.readfileasync (fileName,  "UTF8"). Then ( function (contents) {return Total + parseint (contents, 10);}); Span class= "Hljs-number" >0). Then (function (total) {//total" is ");         
Time
    1. . delay (int ms), Promise
    2. . timeout (int ms [, String message]) Promise
The realization of Promise
    1. Q
    2. Bluebird
    3. Co
    4. When
ASYNC

The async function, like the Promise and Generator functions, is a way to replace the callback function and resolve the asynchronous operation. It is essentially the syntactic sugar of the Generator function. The async function is not part of the ES6, but is included in the ES7.

References (said to be copied can also):



Text/Meteor Hurricane (Jane book author)
Original link: http://www.jianshu.com/p/063f7e490e9a
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".



Text/Meteor Hurricane (Jane book author)
Original link: http://www.jianshu.com/p/063f7e490e9a
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

Organizing asynchronous code with ES6 +promise

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.