generator promise async 读取文件

 1 const fs = require('fs')
 2 
 3 const readFile = (path, options) => {
 4     return new Promise((resolve, reject) => {
 5         fs.readFile(path, options, (err, data) => {
 6             if (err) throw err
 7             resolve(data)
 8         })
 9     })
10 }
11 
12 readFile('data/a.txt', 'utf-8').then(res => {
13     console.log(res) 
14     return readFile('data/a.1.txt', 'utf-8')
15 }).then(res => {
16     console.log(res) 
17     return readFile('data/a.2.txt', 'utf-8')
18 }).then(res => {
19     console.log(res) 
20 })
21 
22 function * gen (){
23     yield readFile('data/a.txt', 'utf-8')
24     yield readFile('data/a.1.txt', 'utf-8')
25     yield readFile('data/a.2.txt', 'utf-8')
26 }
27 
28 let g1 = gen()
29 
30 g1.next().value.then(res => {
31     console.log(res)
32     return g1.next().value
33 }).then(res => {
34     console.log(res)
35     return g1.next().value
36 }).then(res => {
37     console.log(res)
38 })
39 
40 async function async1() {
41     try{
42         let f1 = await readFile('data/a.txt', 'utf-8')
43         let f2 = await readFile('data/a.1.txt', 'utf-8')
44         let f3 = await readFile('data/a.2.txt', 'utf-8')
45         console.log(f1)
46         console.log(f2)
47         console.log(f3)   
48     }catch(e) {
49         console.log(e)
50     }
51 }
52 async1()

data目录下的a.txt  随便定义内容

posted @ 2018-08-18 19:05  gaoxuerong  阅读(219)  评论(0编辑  收藏  举报