Gist-ES6 Promise

Promise is used to asynchronous computations.

The concept of "Promise"

Introduction

"Synchronize asynchronous methods" is always a hot topic.Here, "Promise" is one way to achieve the goal.

Promise Model

Basic Promise Model

In javascript, it's like:

// #1 Create a "Promise" object
const testPromise = new Promise( (resolve, reject) => {
  // resolve("parameters") or reject("parameters")
  // example 1: setTimeout(resolve, 1000, 'parameters')
  // example 2: setTimeout(reject, 1000, 'parameters')
} )

testPromise.then( value => {
    // #2 Monitor the state of "Promise", if state is "fulfilled"
},  value => {
    // #2 Monitor the state of "Promise", if state is "rejected"
})

Chaining promise model

const testPromise = new Promise( (resolve, reject) => {
  // set the state of "Promise" to "fulfilled"
  resolve()
} )

testPromise
    .then( value => {
        // Continue to create "Promise"
        return new Promise( (resolve, reject) => {
            resolve()
        } )
    }, value => {
    })
    .then( value => {
        // Continue to create "Promise"
        return new Promise( (resolve, reject) => {
        resolve('parameters')
        } )
    }, value => {
    })
    .then( value => {
        console.log(value)  // output: 'paramaters'
    }, value => {
    })

Grammar

Initialize

Promise constructor

Chain

Promise.prototype.then()

Catch rejected reason

Promise.prototype.catch()

Resolve or reject parameters directly

Promise.resolve() Promise.reject()

Queue

Promise.all()

Apply fastest promise

Promise.race

Conclusion

There must be lots of ways to synchronize asynchronous methods, however, it's more convenient if a standard emerges so we can build robust program more easily.Obviously, promise is an ideal standard.

Thanks for your reading. Welcome to subscribe my blog by Github.

Post Time: 2017/7/1
Category: Technology/FrontEnd/JavaScript
Author all rights reserved reprint please indicate the source no commercial reprint
Copyright © 2017-2021Terry SuALL RIGHTS RESERVED