ES6 co模块的异步书写

es6之前,异步的回调嵌套太多,书写与阅读都非常麻烦。
若用promise写法,数据从头到尾必须包含在promise内,也不是很方便。

此处介绍基于generator和yeild的co模块,阅读与书写就比较方便了。使用方法如下:

npm install co // 安装

const co = require('co')
function step1() {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            console.log('step1')
            resolve('step1')
        }, 1000)
    })
}
function step2() {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            console.log('step2')
            resolve('step2')
        }, 1000)
    })
}
function step3() {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            console.log('step3')
            resolve('step3')
        }, 1000)
    })
}

co(function *() {
    // 这样顺序书写,会在step1执行完毕后再执行step2;
    // 且resolve传递的值脱离了promise,被传递给了a,b
    var a = yield step1()
    var b = yield step2()
}).then(function(data) {
    // co方法返回的也是一个promise对象,当然可以用then和catch继续书写
    console.log(data)
}).catch(function(err) {
    console.log(err)
})

co(function *() {
    // 这样用数组书写,step1和step2并行执行;
    // 等到step1和step2都执行完毕之后,此个yeild才算执行完毕,才会执行step3
    var res = yeild [
        step1(),
        step2()
    ]
    // res = ['step1', 'step2']
    var c = yeild step3()
})

// 以下代码也是并行处理的一种书写方式
co(function *() {
    var res = yeild {
        1: step1(),
        2: step2()
    }
    var c = yeild step3()
})

THE END!