This time I will bring you a detailed explanation of the use of Promise in ES6. What are the precautions for using Promise in ES6? The following is a practical case, let's take a look.
Of course, this does not mean that it has burst into a full stack. The skills of the whole stack are very concentrated, not only the front-end can write some HTML and some interactions, but the back-end is familiar with the addition, deletion, checking and modification of the database. Everyone who has come into contact with Node must know that Node is famous for its asynchronous (Async) callbacks. Its asynchronicity improves the execution efficiency of the program, but it also reduces the readability of the program. If we have several asynchronous operations, and the latter operation requires the data returned by the previous operation to be executed, then according to the general execution rules of Node, orderly asynchronous operations are usually nested layer by layer. In order to solve this problem, ES6 proposed the implementation of Promise.Meaning
Promise Its general representation is:new Promise( /* executor */ function(resolve, reject) { if (/* success */) { // ...执行代码 resolve(); } else { /* fail */ // ...执行代码 reject(); } } );Among them, the parameter executor in Promise is an executor function, which has two parameters, resolve and reject. There are usually some asynchronous operations inside it. If the asynchronous operation is successful, you can call resolve() to set the We can think of the Promise object as a factory assembly line. For the assembly line, from the perspective of its job functions, it has only three states, one is the initial state (when it is just turned on), and the other is One is that the processed product is successful, and the other is that the processed product fails (some failure occurred). Similarly for the Promise object, it also has three states:
- pending: The initial state, also called the undecided state, is the state after calling the executor executor function when initializing the Promise.
- fulfilled: completion status, which means the asynchronous operation was successful.
- rejected: Failure status means that the asynchronous operation failed.
- The operation is successful: pending -> fulfilled
- Operation failed: pending -> rejected
Method
Promise.prototype.then()
The Promise object contains the then method, Then() returns a Promise object after being called, which means that the instantiated Promise object can be called in a chain, and this then() method can receive two functions, one is the function after successful processing, and the other is the error result. function. As follows:var promise1 = new Promise(function(resolve, reject) { // 2秒后置为接收状态 setTimeout(function() { resolve('success'); }, 2000); }); promise1.then(function(data) { console.log(data); // success }, function(err) { console.log(err); // 不执行 }).then(function(data) { // 上一步的then()方法没有返回值 console.log('链式调用:' + data); // 链式调用:undefined }).then(function(data) { // .... });Here we mainly focus on the status of the Promise object returned after the promise1.then() method is called. Is it pending, fulfilled, or rejected? The status of the returned Promise object is mainly based on the value returned by the promise1.then() method, which is roughly divided into the following situations:
- If a parameter is returned in the then() method value, then the returned Promise will become the receiving state.
- If an exception is thrown in the then() method, the returned Promise will become rejected.
- If the then() method calls the resolve() method, the returned Promise will become the receiving state.
- If the then() method calls the reject() method, the returned Promise will become rejected.
- If the then() method returns a new Promise instance with an unknown state (pending), then the new Promise returned is in an unknown state.
- If the then() method does not explicitly specify resolve(data)/reject(data)/return data, then the new Promise returned is the receiving state, which can be performed layer by layer Pass it down.
var promise2 = new Promise(function(resolve, reject) { // 2秒后置为接收状态 setTimeout(function() { resolve('success'); }, 2000); }); promise2 .then(function(data) { // 上一个then()调用了resolve,置为fulfilled态 console.log('第一个then'); console.log(data); return '2'; }) .then(function(data) { // 此时这里的状态也是fulfilled, 因为上一步返回了2 console.log('第二个then'); console.log(data); // 2 return new Promise(function(resolve, reject) { reject('把状态置为rejected error'); // 返回一个rejected的Promise实例 }); }, function(err) { // error }) .then(function(data) { /* 这里不运行 */ console.log('第三个then'); console.log(data); // .... }, function(err) { // error回调 // 此时这里的状态也是fulfilled, 因为上一步使用了reject()来返回值 console.log('出错:' + err); // 出错:把状态置为rejected error }) .then(function(data) { // 没有明确指定返回值,默认返回fulfilled console.log('这里是fulfilled态'); });
Promise.prototype.catch()
catch()方法和then()方法一样,都会返回一个新的Promise对象,它主要用于捕获异步操作时出现的异常。因此,我们通常省略then()方法的第二个参数,把错误处理控制权转交给其后面的catch()函数,如下:
var promise3 = new Promise(function(resolve, reject) { setTimeout(function() { reject('reject'); }, 2000); }); promise3.then(function(data) { console.log('这里是fulfilled状态'); // 这里不会触发 // ... }).catch(function(err) { // 最后的catch()方法可以捕获在这一条Promise链上的异常 console.log('出错:' + err); // 出错:reject });
Promise.all()
Promise.all()接收一个参数,它必须是可以迭代的,比如数组。
它通常用来处理一些并发的异步操作,即它们的结果互不干扰,但是又需要异步执行。它最终只有两种状态:成功或者失败。
它的状态受参数内各个值的状态影响,即里面状态全部为fulfilled时,它才会变成fulfilled,否则变成rejected。
成功调用后返回一个数组,数组的值是有序的,即按照传入参数的数组的值操作后返回的结果。如下:
// 置为fulfilled状态的情况 var arr = [1, 2, 3]; var promises = arr.map(function(e) { return new Promise(function(resolve, reject) { resolve(e * 5); }); }); Promise.all(promises).then(function(data) { // 有序输出 console.log(data); // [5, 10, 15] console.log(arr); // [1, 2, 3] });
// 置为rejected状态的情况 var arr = [1, 2, 3]; var promises2 = arr.map(function(e) { return new Promise(function(resolve, reject) { if (e === 3) { reject('rejected'); } resolve(e * 5); }); }); Promise.all(promises2).then(function(data) { // 这里不会执行 console.log(data); console.log(arr); }).catch(function(err) { console.log(err); // rejected });
Promise.race()
Promise.race()和Promise.all()类似,都接收一个可以迭代的参数,但是不同之处是Promise.race()的状态变化不是全部受参数内的状态影响,一旦参数内有一个值的状态发生的改变,那么该Promise的状态就是改变的状态。就跟race单词的字面意思一样,谁跑的快谁赢。如下:
var p1 = new Promise(function(resolve, reject) { setTimeout(resolve, 300, 'p1 doned'); }); var p2 = new Promise(function(resolve, reject) { setTimeout(resolve, 50, 'p2 doned'); }); var p3 = new Promise(function(resolve, reject) { setTimeout(reject, 100, 'p3 rejected'); }); Promise.race([p1, p2, p3]).then(function(data) { // 显然p2更快,所以状态变成了fulfilled // 如果p3更快,那么状态就会变成rejected console.log(data); // p2 doned }).catch(function(err) { console.log(err); // 不执行 });
Promise.resolve()
Promise.resolve()接受一个参数值,可以是普通的值,具有then()方法的对象和Promise实例。正常情况下,它返回一个Promise对象,状态为fulfilled。但是,当解析时发生错误时,返回的Promise对象将会置为rejected态。如下:
// 参数为普通值 var p4 = Promise.resolve(5); p4.then(function(data) { console.log(data); // 5 }); // 参数为含有then()方法的对象 var obj = { then: function() { console.log('obj 里面的then()方法'); } }; var p5 = Promise.resolve(obj); p5.then(function(data) { // 这里的值时obj方法里面返回的值 console.log(data); // obj 里面的then()方法 }); // 参数为Promise实例 var p6 = Promise.resolve(7); var p7 = Promise.resolve(p6); p7.then(function(data) { // 这里的值时Promise实例返回的值 console.log(data); // 7 }); // 参数为Promise实例,但参数是rejected态 var p8 = Promise.reject(8); var p9 = Promise.resolve(p8); p9.then(function(data) { // 这里的值时Promise实例返回的值 console.log('fulfilled:'+ data); // 不执行 }).catch(function(err) { console.log('rejected:' + err); // rejected: 8 });
Promise.reject()
Promise.reject()和Promise.resolve()正好相反,它接收一个参数值reason,即发生异常的原因。此时返回的Promise对象将会置为rejected态。如下:
var p10 = Promise.reject('手动拒绝'); p10.then(function(data) { console.log(data); // 这里不会执行,因为是rejected态 }).catch(function(err) { console.log(err); // 手动拒绝 }).then(function(data) { // 不受上一级影响 console.log('状态:fulfilled'); // 状态:fulfilled });
总之,除非Promise.then()方法内部抛出异常或者是明确置为rejected态,否则它返回的Promise的状态都是fulfilled态,即完成态,并且它的状态不受它的上一级的状态的影响。
总结
大概常用的方法就写那么多,剩下的看自己实际需要再去了解。
解决Node回调地狱的不止有Promise,还有Generator和ES7提出的Async实现。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of Promise usage in ES6. For more information, please follow other related articles on the PHP Chinese website!

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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software