zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    [BZOJ1492][NOI2007]货币兑换Cash(斜率优化+CDQ分治)
    [P1768]天路(分数规划+SPFA判负环)
    [BZOJ5109][LOJ #6252][P4061][CodePlus 2017 11月赛]大吉大利,今晚吃鸡!(最短路+拓扑排序+传递闭包+map+bitset(hash+压位))
    [BZOJ1040][ZJOI2008]骑士(环套树dp)
    [P3759][TJOI2017]不勤劳的图书管理员(分块+树状数组)
    [CF665F]Four Divisors
    [LOJ6235]区间素数个数
    [SDOI2015]约数个数和
    [BZOJ3944]Sum
    [BZOJ2671]Calc
  • 原文地址:https://www.cnblogs.com/zhangruiqi/p/9305301.html
Copyright © 2011-2022 走看看