promise 和 async 的用法

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
// 先构造一个 promise 函数
// resolve 和 reject 都是一个函数
// resolve 在成功时调用
// reject 在失败时调用
function promise() {
return new Promise((resolve, reject) => {
let tar = Math.random(0, 1)
if (tar > 0.5) {
console.log('suceess')
setTimeout(function() {
resolve('resolve')
}, 1000)
} else {
console.log('fail')
setTimeout(function() {
reject('reject')
}, 1000)
}
})
}

// then 和 catch 第一个参数为resolve状态时的回调,第二个参数为reject状态时的回调
// catch 相当于 then(null, reject)
promise().then(
(resolve) => console.log('then', resolve)
).catch(
(reject) => console.log('catch', reject)
)


// then 后面还可以接 then 一直链式调用
// 第一个 then 接受的参数是 resolve 函数传过来的参数
// 第二个 then 接受一个参数是第一个 then 返回的值
promise().then(
(resolve) => (resolve + 1) // 接受 resolve 返回 resolve + 1
).then(
(plusOne) => console.log(plusOne) // 接受 resolve +1 并打印
).catch(
(reject) => console.log('catch', reject)
)

async

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
// 同样需要一个 promise 对象
function promise() {
return new Promise((resolve, reject) => {
let tar = Math.random(0, 1)
if (tar > 0.5) {
console.log('success')
setTimeout(function() {
resolve('resolve')
}, 1000)
} else {
console.log('fail')
setTimeout(function() {
reject('reject')
}, 1000)
}
})
}

// 只是调用的方法跟 then/catch 不一样
// async 函数执行时,一旦遇到 await 就会先返回,等异步操作完成,再接着执行后面的操作
async function async() {
const res = await promise()
console.log(res)
console.log('wait')
return res
}

// async 函数返回 promise 对象
// 只有函数内的 await 语句全部执行完,或者遇到 return 或 抛出错误,才会发生状态改变
// 如果发生错误或状态为 reject 则执行 catch
async().then(
(res) => console.log(res)
).catch(
(e) => console.log(e)
)