js中的异步

promise

  • 应用
    function ajax(url){
         return new Promise(function(resolve,reject){
               let xhr = new XMLHttpRequest()
               xhr.open('GET',url)
               xhr.responseType = 'json'
               xhr.onload = function(){
                   if(this.status===200){
                        resolve(this.response)
                   }else{
                       reject(new Error(this.statusText))
                   }
               }
               xhr.send()
         })
    }
    ajax('./package.jso1n').then(res=>{
         console.log(res)
    }).catch(err=>{
         console.log(err)
    })
  • 链式调用
  1. then返回一个新的promise对象,
  2. 下一个then为上一个then返回的promise注册回调
  3. 前面then的返回值会作为后面then的回调参数
  4. 如果then回调返回promise对象,后面的then会等待它的结果
  • 异常处理 错位代码或者手动throw error会被reject捕获,在catch中输出,和then中传第二个函数效果一样 then第二个回调只能捕获上一个promise的错误,catch能捕获所有的
  const r = ajax('./package.json').then(res => {
        console.log(res)
        return ajax('./package.json')
    }).catch(err=>{
         console.log(err)
    })
    .then(res => {
        console.log(res) //返回json数据
    }).then(res => {
        console.log(res)
        return 1
    }).then(res => {
        console.log(res) //返回1
        return 2
    }).then(res => {
        console.log(res) //返回2
    })
    console.log(r)
  • promise 静态方法
  1. promise.resolve(data) 将一个值转化为promise对象,若传入pomise,原样返回
  2. promise.reject(data) 返回失败的promise状态
  3. promise.all[promise对象1,primise对象2] 所有任务结束才会结束
  4. promise.race[promise对象1,primise对象2] 哪个结果获得的快,就返回那个结果,不管结果本身是成功状态还是失败状态。

宏任务 微任务

微任务 promise process.nextTick
宏任务 setTimeout setInterval I/O script
同一次事件循环中 微任务永远在宏任务之前执行

   setTimeout(function(){
        console.log('定时器开始啦')
    });
    
    new Promise(function(resolve){
        console.log('马上执行for循环啦');
        for(var i = 0; i < 10000; i++){
            i == 99 && resolve();
        }
    }).then(function(){
        console.log('执行then函数啦')
    });
    
    console.log('代码执行结束');
  • 首先执行script下的宏任务,遇到setTimeout,将其放到宏任务的【队列】里
    遇到 new Promise直接执行,打印"马上执行for循环啦"
    遇到then方法,是微任务,将其放到微任务的队列里
    打印 "代码执行结束"
    本轮宏任务执行完毕,查看本轮的微任务,发现有一个then方法里的函数, 打印"执行then函数啦"
    到此,本轮的event loop 全部完成。
    下一轮的循环里,先执行一个宏任务,发现宏任务的【队列】里有一个 setTimeout里的函数,执行打印"定时器开始啦"

generator

   //generator 
    function * foo(){
        console.log('start')
        try{
            debugger
            const res = yield 'foo'
            console.log( res )
        }catch(e){
            console.log(e)
        }
      
    }
   const res = foo()
   console.log(res.next('111'))    //{value: "foo", done: false}  
    
  // console.log(res.next('111'))  //参数会作为yield的返回值
    res.throw(new Error('gen error'))
  • ajax 方案
function* main() {
        try{
            const user = yield ajax('package.json')
            console.log(user)
            const user2 = yield ajax('package-lock.json')
            console.log(user2)
        }catch(e){
            console.log(e)
        }
      
    }
   const g = main()
    // const result = g.next()
    // result.value.then(res => {
    //     const result2 = g.next(res)
    //     if (result2.done) return
    //     result2.value.then(res => {
    //         g.next(res)

    //     })
    // })
    function handleResult(result){
           if(result.done) return
           result.value.then(res=>{
             handleResult(g.next(res))
           },err=>{
                g.throw(err)
           })
    }
    handleResult(g.next())

async/await

  • generator语法糖 async函数会返回promise对象
     async function main() {
        try{
            const user = await ajax('package.json')
            console.log(user)
            const user2 = await ajax('package-lock.json')
            console.log(user2)
        }catch(e){
            console.log(e)
        }
      
    }
    const promise = main()
    promise.then(res=>{
         console.log('complete')
    })
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容