Home >Web Front-end >JS Tutorial >Introducing the Promise object of ES6
I am very excited about the new feature discussed today because it is the most amazing feature in ES6.
Promise object is a solution for asynchronous programming. The so-called Promise is simply a container that contains the result of an event that may end in the future.
Promise contains three states, pending, fulfilled, and rejected.
Performs from pending to fulfilled, or from pending to rejected.
The following is the generation of a Promise instance
// es5 写法 const promise = new Promise(function(resolve, reject) { if (/*这里填写操作(一般是异步操作)*/) { resolve(value); } else { reject(error) } })
// es6 写法,以后默认使用es6语法 const promiseEs = new Promise((resolve, reject) => { if (/*操作*/) { resolve(value); } else { reject(error); } })
The operation part is generally an asynchronous method. Resolve and reject are the official methods of es6 to obtain the return of the operation part. Result
Usage of promise
promise.then((value) => { console.log("success" + value); }, (error) => { console.log("error" +error); })
Thethen method accepts two callback functions as parameters. The first method is called when the Promise object status changes from pending to fulfilled. The two methods are called when the status changes from pending to rejected.
In addition, the above usage method can be written in a form similar to try/catch, and the processing of rejected is stripped out and placed in catch. Use of promise 2
promise.then((value) => { console.log("success" + value); }).catch((error) => { console.log("error" +error); })
Related recommendations:
Overview of new features of ES6_javascript skills
Detailed explanation of Generator_Basic knowledge in JavaScript ES6
The above is the detailed content of Introducing the Promise object of ES6. For more information, please follow other related articles on the PHP Chinese website!