• js异步任务处理方式


    一、es6(es2015)之前:使用原始的callback函数,会陷入回掉地域

    this.$http.jsonp('/login', (res) => {
      this.$http.jsonp('/getInfo', (info) => {
        // do something
      })
    })

    二、es6(es2015):

      1. Promise 

    // 点击确定按钮时,获取面值列表
                getFaceResult () {
                    this.getLocation(this.phoneNum)
                        .then(res => {
                            if (res.status === 200 && res.data.success) {
                                let province = res.data.obj.province;
                                let city = res.data.obj.city;
    
                                this.getFaceList(province, city)
                                    .then(res => {
                                        if(res.status === 200 && res.data.success) {
                                            this.faceList = res.data.obj
                                        }
                                    })
                            }
                        })
                        .catch(err => {
                            console.log(err)
                        })
                }

    Promise 的方式虽然解决了 callback hell,但是这种方式充满了 Promise的 then() 方法,如果处理流程复杂的话,整段代码将充满 then。语义化不明显,代码流程不能很好的表示执行流程。

      2. Generator 

    function* G() {
        const a = yield 100
        console.log('a', a)  // a aaa
        const b = yield 200
        console.log('b', b)  // b bbb
        const c = yield 300
        console.log('c', c)  // c ccc
    }
    const g = G()
    g.next()    // value: 100, done: false
    g.next('aaa') // value: 200, done: false
    g.next('bbb') // value: 300, done: false
    g.next('ccc') // value: undefined, done: true

    Generator 的方式解决了 Promise 的一些问题,流程更加直观、语义化。但是 Generator 的问题在于,函数的执行需要依靠执行器,每次都需要通过 g.next() 的方式去执行。

    三、es2017

     1. async/await 

    async function testResult() {
        let first = await doubleAfter2seconds(30);
        let second = await doubleAfter2seconds(50);
        let third = await doubleAfter2seconds(30);
        console.log(first + second + third);
    }

    async 函数完美的解决了上面两种方式的问题。流程清晰,直观、语义明显。操作异步流程就如同操作同步流程。同时 async 函数自带执行器,执行的时候无需手动加载。

    参考链接:https://segmentfault.com/a/1190000010244279

  • 相关阅读:
    设置 nextjs build 时,忽略 page 目录下相关文件
    Resource Override 之调试线上 js
    nodejs npm 基础命令
    禁止选择或禁止复制网页数据
    对上传的图片进行格式校验以及安全性校验
    docker 设置阿里云镜像加速
    JS 格式化输出时间
    dotnet core 实现 IActionResult
    win10 visual studio 设置默认管理员权限启动
    Windows 环境部署 RabbitMQ
  • 原文地址:https://www.cnblogs.com/zhangruiqi/p/9305301.html
Copyright © 2020-2023  润新知