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 });
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
- ##Promise.resolve()
- Promise.reject()
- Promise.prototype.then()
- Promise.prototype.catch()
- Promise.all() // All completed
var p = Promise.all([p1,p2,p3]);
- Promise.race() // Racing, just complete one
somePromise().then(functoin(){ // do something });We You can do three things,
1. return 另一个 promise2. return 一个同步的值 (或者 undefined)3. throw 一个同步异常 ` throw new Eror('');`1. Encapsulate synchronous and asynchronous code
"
new Promise(function (resolve, reject) {
resolve(someValue);
});
"
写成
"
Promise.resolve(someValue);
"
2. Capture synchronization exceptions new Promise(function (resolve, reject) { throw new Error('悲剧了,又出 bug 了');
}).catch(function(err){ console.log(err);
});
If it is synchronous code, it can be written asPromise.reject(new Error("什么鬼"));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
});
4. Get the return value of two Promise1. .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 thisvar 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 declare it first, there is a waste of resources and memory Risk of leakage
- Cannot be used in the context of an expression
- Less efficient
"var join = Promise.join;join(getPictures(), getComments(), getTweets(),
function(pictures, comments, tweets) {
console.log("in total: " + pictures.length + comments.length + tweets.length);
});
"
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);
});
"
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) {
err.forEach(function(e) {console.error(e.stack );
});
});;
" 有可能,失败的 promise 比较多,导致,Promsie 永远不会 fulfilled11. .map(Function mapper [, Object options])
用于处理一个数组,或者 promise 数组,
Option: concurrency and found
map(..., {concurrency: 1});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); });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: 9ms11. .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
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 (www.php.cn)!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor