The real problem with callback functions is that they deprive us of the ability to use the return and throw keywords. Promise solves all this well. Promise in js
The real problem with callback functions is that they deprive us of the ability to use the return and throw keywords. Promise solves all this well.
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. ES6 aims to enable the JavaScript language to write large and complex applications and become an enterprise-level development language.
Concept
ES6 native provides Promise objects.
The so-called Promise is an object used to transmit messages for asynchronous operations. It represents an event that will be known as a result in the future (usually an asynchronous operation) and provides a unified API for further processing.
The Promise object has the following two features.
(1) The object state is not affected by the outside world. The Promise object represents an asynchronous operation in three states: Pending (in progress), Resolved (completed, also called Fulfilled), and Rejected (failed ). Only the result of an asynchronous operation can determine the current status. Other operations cannot change this status. This is also the origin of the name Promise. It means "Promise", indicating that other means cannot be changed.
(2) once the status changes, it will not change any more. You can get this result at any time. There are only two possibilities for changing the state of a Promise object: From Pending to Resolved and from Pending to Rejected. As long as these two situations occur, the status will be solidified and will not change any more. This result will be maintained. Even if the change has already occurred, you can add a callback function to the Promise object and get the result immediately. This is completely different from the Event. The Event is characterized by listening if you miss it.
With the Promise object, you can express asynchronous operations in the synchronous operation process, avoiding nested callback functions. In addition, the Promise object provides a unified interface, making it easier to control asynchronous operations.
Promise also has some disadvantages. First, the Promise cannot be canceled. Once it is created, it will be executed immediately and cannot be canceled midway through. Second, if the callback function is not set, the internal error thrown by Promise will not be reflected to the outside. Third, when you are in Pending status, you cannot know the current progress to which stage (which is about to be completed at the beginning ).
Var promise = new Promise (function (resolve, reject) {if (/* Asynchronous Operation successful */) {resolve (value );} else {reject (error) ;}}); promise. then (function (value) {// success}, function (value) {// failure });
The Promise constructor accepts a function as a parameter. The two parameters of the function are the resolve method and reject method.
If the asynchronous operation is successful, use the resolve method to change the state of the Promise object from incomplete to successful (that is, from pending to resolved );
If the asynchronous operation fails, use the reject method to change the state of the Promise object from incomplete to failed (that is, from pending to rejected ).
Basic APIs
Promise. resolve ()
Promise. reject ()
Promise. prototype. then ()
Promise. prototype. catch ()
Promise. all () // all completed
var p = Promise.all([p1,p2,p3]);
Promise. race () // race, complete one
Advanced
The magic of promises is to give us the previous return and throw. Each Promise will provide a then () function and a catch () function, which is actually a then (null,...) function,
somePromise().then(functoin(){ // do something });
We can do three things,
1. return another promise2. return a synchronized value (or undefined) 3. throw a synchronization exception 'Throw new Eror ('');'
1. encapsulate synchronous and asynchronous code
"New Promise (function (resolve, reject) {resolve (someValue) ;});" written as "Promise. resolve (someValue );"
2. Capture synchronization exceptions
New Promise (function (resolve, reject) {throw new Error ('tragedy, another bug ');}). catch (function (err) {console. log (err );});
For synchronous code, you can write
Promise. reject (new Error ("What ghost "));
3. capture multiple exceptions for more precise capture
somePromise.then(function() { return a.b.c.d();}).catch(TypeError, function(e) { //If a is defined, will 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 at all}).catch(function(e) { //Generic catch-the rest, error wasn't TypeError nor //ReferenceError});
4. Get the return values of two Promise
1. Call the then method sequentially. 2. Set a higher-level scope. 3. spread
5. finally
It will be executed in any situation, usually after 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.
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 many differences,
You must first declare that there is a risk of resource waste and Memory leakage.
Cannot be used in the context of an expression.
Lower efficiency
7. all. It is very useful for processing a list of dynamic and even-sized Promise 8. join. Very suitable for Promise processing multiple Separation
"var join = Promise.join;join(getPictures(), getComments(), getTweets(), function(pictures, comments, tweets) { console.log("in total: " + pictures.length + comments.length + tweets.length);});"
9. props. Process a map set of promise. Only one failure exists, and all execution ends.
"Promise.props({ pictures: getPictures(), comments: getComments(), tweets: getTweets()}).then(function(result) { console.log(result.tweets, result.pictures, result.comments);});"
10. any, some, and 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 );
});
});;
"It is possible that many failed promise results. As a result, Promsie will never be fulfilled.
11. map (Function mapper [, Object options])
Used to process an array or promise array,
Option: concurrency and found
map(..., {concurrency: 1});
There is no limit on the number of concurrent reading files.
var Promise = 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, function(fileName) { 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);});
Result
$ 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
11. 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); });}, 0).then(function(total) { //Total is 30});
12. Time
. Delay (int MS)-> Promise
. Timeout (int MS [, String message])-> Promise
Promise implementation
Q
Bluebird
Co
When
ASYNC
Like Promise and Generator functions, async functions are used to replace callback functions and solve asynchronous operations. It is essentially the syntactic sugar of the Generator function. The async function is included in ES7 instead of ES6.
The above is the content of Promise, an artifact in Javascript. For more information, see PHP Chinese website (www.php1.cn )!