Home > Web Front-end > JS Tutorial > body text

Introducing the Promise object of ES6

坏嘻嘻
Release: 2018-09-14 14:11:18
Original
1443 people have browsed it

I am very excited about the new feature discussed today because it is the most amazing feature in ES6.​ ​

Introduction

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)
        }
    })
Copy after login
   // es6 写法,以后默认使用es6语法   const promiseEs = new Promise((resolve, reject) => {        if (/*操作*/) {
            resolve(value);
        } else {
            reject(error);
        }
    })
Copy after login

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template