0%

ES6中的promise对象

ES6中的promise对象

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
Promise 是抽象异步处理对象以及对其进行各种操作的组件
简而言之, 就是让异步操作变得好看一些

Promise 的用法如下
*/

// 将 fs.readFile 的操作封装成 promise
// 这样就可以使用 promise 的 api 了
const readFile = function(filename) {
// 一般前端的写法
// return new Promise(function(resolve, reject) {})
const p = new Promise(function(resolve, reject) {
const fs = require('fs')
const options = {
encoding: 'utf8'
}
fs.readFile(filename, options, function(error, content) {
if (error !== null) {
reject(error)
} else {
resolve(content)
}
})
})

return p
}

// 使用 promise 读取文件就不用写成回调的形式了
// 直接按照同步的写法就好了
// 可以无限 then, 只要你保证上一个 then 返回了东西即可
let promise = readFile('foo.txt')
promise.then(function(content) {
console.log('debug file content', content)
const c = content + ' suffix1'
return c
}, function(error) {
console.log('debug error message', error)
}).then(function(c1) {
console.log('second then', c1)
const c = c1 + ' suffix2'
return c
}).then(function(c) {
console.log('third then', c)
})

// 上面的写法也可以写成下面这样
// 把 reject 的操作放在 catch 里面
promise.then(function(content) {
console.log('debug file content', content)
}).catch(function(error) {
console.log('debug error message', error)
})

// 有时候会碰到批量执行异步操作,如果直接用循环 + 调用函数的形式会比较麻烦
// 使用 Promise.all 就很方便了
// all 方法是直接挂在 Promise 类上的
// 而 then catch 这些方法是挂在原型上
const fileList = [
't1.txt',
't2.txt',
't3.txt',
]
const list = fileList.map(function(item) {
const r = readFile(item)
return r
})

Promise.all(list).then(function(content) {
console.log('content', content)
})

/*
这是一个完整的参考, 如果有兴趣以后可以翻翻看, 但是现在没必要看了
http://liubin.org/promises-book/
*/