# 异步编程

callback -> promise -> generator + co -> async+await(语法糖)

思路:

本地有三个文件,三个文件的中第一个文件存放第二个文件的地址,第二个文件存放第三个文件的地址,第三个文件存放最后的结果,从文件一读取文件二的地址,根据这个地址读取文件三的内容。

准备工作:

我们在本地建立三 txt 个文件:one.txt 里面内容放 two.txt、two.txt 里面内容放 three.txt、three.txt 里面放“恭喜你完成了本次的训练!!”

# 1.callback

存在回调地狱的问题,导致代码难以维护

let fs = require("fs")
function getDate(url, callback) {
  fs.readFile(url, "utf8", function (err, data) {
    callback && callback(data)
  })
}
getDate("one.txt", function (data) {
  console.log("1", data)
  getDate(data, function (data) {
    console.log("2", data)
    getDate(data, function (data) {
      console.log("3", data)
    })
  })
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

结果

//1 two.txt
//2 three.txt
//3 恭喜你完成了本次的训练!!!
1
2
3

# 2.promise

let fs = require("fs")
function getDate(url) {
  return new Promise(function (resolve, reject) {
    let date = fs.readFile(url, "utf8", function (err, date) {
      err ? reject(err) : resolve(date)
    })
  })
}
getDate("one.txt")
  .then(
    function (success) {
      console.log("1", success)
      return getDate(success)
    },
    function (fail) {
      console.log("1", fail)
    }
  )
  .then(
    function (success) {
      console.log("2", success)
      return getDate(success)
    },
    function (fail) {
      console.log("1", fail)
    }
  )
  .then(
    function (success) {
      console.log("3", success)
    },
    function (fail) {
      console.log("1", fail)
    }
  )
结果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//1 two.txt
//2 three.txt
//3 恭喜你完成了本次的训练!!!
1
2
3

# 3.generator

配合 promise 使用

let fs = require("fs")
let bluebird = require("bluebird")
let read = bluebird.promisify(fs.readFile) //使其promise化
function* getDateLast() {
  let date1 = yield read("one.txt", "utf8")
  let date2 = yield read(date1, "utf8")
  let date3 = yield read(date2, "utf8")
  let date4 = yield read(date3, "utf8")
}
var content = getDateLast()
content.next().value.then(function (data) {
  console.log("2" + data)
  content.next(data).value.then(function (data) {
    console.log("3" + data)
    content.next(data).value.then(function (data) {
      console.log("4" + data)
    })
  })
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

结果

//2two.txt
//3three.txt
//4恭喜你完成了本次的训练!!!
1
2
3

# 4.async + await

配合 promise 使用

let fs = require("fs")
let bluebird = require("bluebird")
let read = bluebird.promisify(fs.readFile) //使其promise化
async function getDate(date) {
  let date1 = await read(date, "utf8")
  let date2 = await read(date1)
  let date3 = await read(date2)
  return date3
}
getDate("one.txt").then(function (success) {
  console.log("success" + success)
})
1
2
3
4
5
6
7
8
9
10
11
12

结果

//success恭喜你完成了本次的训练!!!
1