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.
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 });
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).
var p = Promise.all([p1,p2,p3]);
somePromise().then(functoin(){ // do something });
1. return 另一个 promise2. return 一个同步的值 (或者 undefined)3. throw 一个同步异常 ` throw new Eror('');`
" new Promise(function (resolve, reject) { resolve(someValue); }); " 写成 " Promise.resolve(someValue); "
new Promise(function (resolve, reject) { throw new Error('悲剧了,又出 bug 了'); }).catch(function(err){ console.log(err); });
Promise.reject(new Error("什么鬼"));
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 });
1. .then 方式顺序调用2. 设定更高层的作用域3. spread
任何情况下都会执行的,一般写在 catch 之后
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; });
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; });
"var join = Promise.join;join(getPictures(), getComments(), getTweets(), function(pictures, comments, tweets) { console.log("in total: " + pictures.length + comments.length + tweets.length); }); "
" Promise.props({ pictures: getPictures(), comments: getComments(), tweets: getTweets() }).then(function(result) { console.log(result.tweets, result.pictures, result.comments); }); "
"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) {
console.error(e.stack );
});
});;
" 有可能,失败的 promise 比较多,导致,Promsie 永远不会 fulfilled
用于处理一个数组,或者 promise 数组,
map(..., {concurrency: 1});
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); });
$ 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
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 });
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)!