123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- 1.进入到 async1,发现同步任务,输出'async1 start'
- 2.遇到了await,进入到async2,碰到定时器,加入到异步队列里面的宏任务
- 3.在async2 有一个同步任务 直接输出'async2'
- 4.由于await 阻塞了后面代码的执行 将后面的代码加入微任务 所以向下去找
- 5.碰到了定时器 加入到宏任务里
- 6.碰到同步任务 输出'start'
- 7.同步代码执行完毕 先执行微任务
- 8.先输出微任务里面的 同步任务 输出'async1 end'
- 9.微任务里面有定时器 加入到宏任务里
- 10.微任务执行完毕 执行宏任务
- 11.宏任务队列里面有3个任务
- 12.按照顺序执行 timer2=>timer3=>timer1
- async 函数
- 1.函数返回值返回Promise对象
- 2.Promise对象结果由async里面的返回值决定
- await函数
- 1.必须写在async里面
- 2.如果遇到await函数 函数后面的代码会被阻止 加入微任务队列里面
- <script>
- /* async function timeout(){
- // throw new Error('rejected')
- return 'hello word'
- }
- timeout().then(val =>{
- console.log(val)
- })
-
- // console.log(timeout())
- console.log(1111) */
- /* await 方法 会阻塞函数内部处于它后面的代码 */
- /* async function fn1(){
- console.log(1)
- await fn2()
- console.log(2)//加入微任务队列
- }
- async function fn2(){
- console.log('fn2')
- }
- fn1()
- console.log(3) */
- /* async function async1() {
- console.log('async1 start')
- await async2()
- console.log('async1 end')
- setTimeout(() => {
- console.log('timer1')
- }, 0)
- }
- async function async2() {
- setTimeout(() => {
- console.log('timer2')
- }, 0)
- console.log('async2')
- }
- async1()
- setTimeout(() => {
- console.log('timer3')
- }, 0)
- console.log('start') */
- /* await function fn2(){
- console.log(2)
- }
- fn2() */
- /* async function fn1(){
- console.log(333)
- await fn2()
- console.log(111)
- }
- async function fn2(){
- throw new Error('rejected')
- }
- fn1()
- console.log(2222) */
- async function fn1(){
- console.log(1)
- await fn2()
- console.log(2)
- setTimeout(()=>{
- console.log(3)
- },0)
- }
- async function fn2(){
- console.log(4)
- await fn3()
- console.log(5)
- }
- async function fn3(){
- setTimeout(()=>{
- console.log(6)
- },0)
- }
- fn1()
- console.log(7)
- //1475263
- //1472563
- </script>
- </body>
- </html>
|