苏溪云
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.

感谢你的阅读。欢迎通过微信(扫描下方二维码)或Github订阅我的博客。

微信公众号:苏溪云的博客

发布时间: 7/1/2017
分类: 技术/前端/JavaScript
作者版权所有,转载请注明出处,禁止商业转载