logo头像
Snippet 博客主题

Node异步流程控制的发展

第一阶段 回调函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 第一阶段 回调函数
function readFile (cb) {
fs.readFile('./package.json', (err, data) => {
if (err) return cb(err)

cb(null, data)
})
}

readFile((err, data) => {
if (!err) {
data = JSON.parse(data)

console.log(data.name)
}
})

第二阶段 Promise

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 第二阶段 Promise
function readFileAsync (path) {
return new Promise((resolve, reject) => {
fs.readFile(path, (err, data) => {
if (err) reject(err)
else resolve(data)
})
})
}

readFileAsync('./package.json')
.then(data => {
data = JSON.parse(data)

console.log(data.name)
})
.catch(err => {
console.log(err)
})

第三个阶段 co + Generator Function + Promise

1
2
3
4
5
6
7
8
9
10
11
// 第三个阶段 co + Generator Function + Promise
const co = require('co')
const util = require('util')

co(function *() {
let data = yield util.promisify(fs.readFile)('./package.json')

data = JSON.parse(data)

console.log(data.name)
})

第四个阶段 Async 统一世界

1
2
3
4
5
6
7
8
9
10
11
12
// 第四个阶段 Async 统一世界
const readAsync = util.promisify(fs.readFile)

async function init () {
let data = await readAsync('./package.json')

data = JSON.parse(data)

console.log(data.name)
}

init()