The artifact in Javascript - Promise

黄舟
Release: 2017-02-10 09:58:38
Original
994 people have browsed it

Promise in js

The real problem with callback functions is that they take away our ability to use the return and throw keywords. And Promise solves all this very well.

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

ECMAScript is the international standard for the JavaScript language, and JavaScript is the implementation of ECMAScript. The goal of ES6 is to enable the JavaScript language to be used to write large and complex applications and become an enterprise-level development language.

Concept

ES6 natively provides Promise objects.

The so-called Promise is an object used to transmit messages for asynchronous operations. It represents an event (usually an asynchronous operation) whose result is not known until the future, and this event provides a unified API for further processing.

Promise objects have the following two characteristics.

(1) The status of the object is not affected by the outside world. The Promise object represents an asynchronous operation and has three states: Pending (in progress), Resolved (completed, also known as Fulfilled) and Rejected (failed). Only the result of the asynchronous operation can determine the current state, and no other operation can change this state. This is also the origin of the name Promise, which means "commitment" in English and means that it cannot be changed by other means.

(2) Once the status changes, it will not change again, and this result can be obtained at any time. There are only two possibilities for the state of a Promise object to change: from Pending to Resolved and from Pending to Rejected. As long as these two situations occur, the state will be solidified and will not change again, and will maintain this result. Even if the change has already occurred, if you add a callback function to the Promise object, you will get the result immediately. This is completely different from an event. The characteristic of an event is that if you miss it and listen again, you will not get the result.

With the Promise object, asynchronous operations can be expressed as a synchronous operation process, avoiding layers of nested callback functions. In addition, Promise objects provide a unified interface, making it easier to control asynchronous operations.

Promise also has some disadvantages. First of all, Promise cannot be canceled. Once it is created, it will be executed immediately and cannot be canceled midway. Secondly, if the callback function is not set, errors thrown internally by Promise will not be reflected externally. Third, when in the Pending state, it is impossible to know which stage the current progress is (just started or about to be completed).

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

The Promise constructor accepts a function as a parameter. The two parameters of the function are the resolve method and the reject method.

If the asynchronous operation is successful, use the resolve method to change the state of the Promise object from "uncompleted" to "successful" (that is, from pending to resolved);

If the asynchronous operation fails , then use the reject method to change the state of the Promise object from "uncompleted" to "failed" (that is, from pending to rejected).

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]);
    Copy after login

  6. Promise.race() // Racing, just complete one

Advanced

The wonder of promises is that given our previous return and throw, each Promise will provide a then() function and a catch(), which is actually a then(null, ...) function.

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

We You can do three things,

1. return 另一个 promise2. return 一个同步的值 (或者 undefined)3. throw 一个同步异常 ` throw new Eror('');`
Copy after login

1. Encapsulate synchronous and asynchronous code

" new Promise(function (resolve, reject) { resolve(someValue); }); " 写成 " Promise.resolve(someValue); "
Copy after login

2. Capture synchronization exceptions

new Promise(function (resolve, reject) { throw new Error('悲剧了,又出 bug 了'); }).catch(function(err){ console.log(err); });
Copy after login

If it is synchronous code, it can be written as

Promise.reject(new Error("什么鬼"));
Copy after login

3. Multiple exception capture, more accurate 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 });
Copy after login

4. Get the return value of two Promise

1. .then 方式顺序调用2. 设定更高层的作用域3. spread
Copy after login

5. finally

任何情况下都会执行的,一般写在 catch 之后
Copy after login

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; });
Copy after login

Or you can do this

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; });
Copy after login

However, there are many differences,

  1. You must declare it first, there is a waste of resources and memory Risk of leakage

  2. Cannot be used in the context of an expression

  3. Less efficient

7. all. Very useful for processing a dynamically sized Promise list

8. join. Ideal for handling multiple detached Promise

"var join = Promise.join;join(getPictures(), getComments(), getTweets(), function(pictures, comments, tweets) { console.log("in total: " + pictures.length + comments.length + tweets.length); }); "
Copy after login

9. props. Handle a map collection of promises. Only if one fails, all executions end

" Promise.props({ pictures: getPictures(), comments: getComments(), tweets: getTweets() }).then(function(result) { console.log(result.tweets, result.pictures, result.comments); }); "
Copy after login

10. 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) {
Copy after login

err.forEach(function(e) {

console.error(e.stack );
});
});;

" 有可能,失败的 promise 比较多,导致,Promsie 永远不会 fulfilled
Copy after login

11. .map(Function mapper [, Object options])

用于处理一个数组,或者 promise 数组,
Copy after login

Option: concurrency and found

map(..., {concurrency: 1});
Copy after login

The following is unlimited number of concurrency, reading file information

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); });
Copy after login

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 Infinity reading files: 9ms
Copy after login

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 });
Copy after login
12. Time

  1. .delay(int ms) -> Promise

  2. ##.timeout(int ms [, String message] ) -> Promise
  3. Promise implementation

    q
  1. ##bluebird
  2. co
  3. when

ASYNC

The async function, like the Promise and Generator functions, is a method used to replace callback functions and solve asynchronous operations. It is essentially syntactic sugar for the Generator function. async functions are not part of ES6, but are included in ES7.

The above is the content of Promise, the artifact in Javascript. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!