JavaScript 异步编程
# JavaScript 异步编程
# 定时器
console.log(1)
setTimeout() => {
console.log(2)
}
console.log(3)
// 输出结果是 1 3 2
// 往下执行时 不会等待setTimeout定时器的结束 而是直接向下继续执行
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# ajax 请求
//无论是使用原生的 XMLHttpRequest 还是 Jquery 的ajax 还是是 axios 都是异步的
$.ajax({
method:'',
url:'',
success: function(data) {
// data 就是响应结果
}
})
// 异步代码 往往都伴随一个回调函数来接受结果 回头调用
axios({
methos:'',
url:''
}).then(res => {
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 1. callback 回调函数
有时候,我们需要在异步操作的结果中执行另外一个异步操作
axios({
methos:'',
url:''
}).then(res => {
axios({
methos:'',
url:''
}).then(res => {
})
})
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
当出现类型上面的嵌套异步时,非常不便于阅读和理解
# 2. Promise
new Promist((resovle,reject) => {
setTimeout(() => {
resolve() // 在Promise中 成功resolve 失败 reject
},1000)
})
1
2
3
4
5
2
3
4
5
# 3.Generator 生成器函数 (淘汰了)
# 4. Async 函数 (推荐)
有了 Async 函数,可以极大了简化我们的异步操作,前提是你的异步操作支持 Promise
如 axios 支持 Promiose, 所以我们可以使用 async 函数调用优化它,任何异步如果支持 promise 则都可以使用 Async 函数来使用
axios({
methos:'',
url:''
}).then(res => {
})
// async 只能用于函数 只要是函数都可以被标记为async,无论这个函数是什么形式
async function main () {
// 通过 async-await 我们可以像屑同步一样来写异步代码
// 使用await关键字的父函数必须加async
const res =await axios({ //await等待,只有 await 后面的操作结束了,代码才会继续往后执行
methos:'',
url:''
})
console.log(res)
const res2 =await axios({ //res2不会马上执行 要等 res 请求结束后才会执行
methos:'',
url:''
})
console.log(res2)
}
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
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
# Async 的 返回值
async function main() {
return 123
//相对应 async 不会把不是promise对象的返回值返回
//return new Promise(resolve => {
//resolve(123)
//})
}
const data = main()
console.log(data) //返回为一个 Promise对象
// async 始终返回一个Promise对象 如果这个返回值不是Promise对象则封装成Promise对象
//第一种方式获取值 用then获取
mian().then(data => {
console.log(data) //promise对象用then返回结果
})
//第二种方式获取值 用await获取
async function main2(){
const data = await mian()
console.log(data)
}
main2()
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# async 函数的错误处理
使用 catch 捕获异常
async function main() {
JSON.parse('123124')
return 123
}
main().then(res => {
console.log(123)
}).catch(err => {
console.log('发生异常',errw)
})
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
推荐使用 try-catch 捕获
async function main2() {
try{
// 如果try 里面的代码遇到异常,则停止执行try里面下面的代码,进入catch
const data =await main()
console.log(data)
} catch (err) {
console.log('异常')
}
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
编辑 (opens new window)
上次更新: 2023/12/06, 01:31:48