1

问题描述
连接转自
1、错误尝试

<script>
    function getSomething() {
        var r = 0;
        setTimeout(function() {
          r = 2;
        }, 10);
        return r;
    }
     
    function compute() {
         var x = getSomething();
         alert(x * 2);
    }
    compute();
</script>

弹出的不是4,而是0,后来知道这是异步的问题,

2、 回调函数

<script>
    function getSomething(cb) {
     var r = 0;
     setTimeout(function() {
     r = 2;
     cb(r);
     }, 10);
    }
     
    function compute(x) {
     alert(x * 2);
    }
    getSomething(compute);
</script>

3、promise

<script>
    function getSomething() {
         var r = 0;
         return new Promise(function(resolve) {
         setTimeout(function() {
          r = 2;
          resolve(r);
         }, 10);
     });
    }
     
    function compute(x) {
         alert(x * 2);
    }
    getSomething().then(compute);
</script>

4、generator

<script>
    function getSomething() {
         var r = 0;
         setTimeout(function() {
         r = 2;
         it.next(r);
         }, 10);
    }
     
    function *compute(it) {
         var x = yield getSomething();
         alert(x * 2);
    }
    var it = compute();
    it.next();
</script>

5.promise + generator

<script>
    function getSomething() {
         var r = 0;
         return new Promise(function(resolve) {
         setTimeout(function() {
              r = 2;
              resolve(r);
         }, 10);
         });
    }
     
    function *compute() {
         var x = yield getSomething();
         alert(x * 2);
    }
    var it = compute();
    it.next().value.then(function(value) {
         it.next(value);
    });
</script>

6.async

<script>
    function getSomething() {
         var r = 0;
         return new Promise(function(resolve) {
         setTimeout(function() {
          r = 2;
          resolve(r);
         }, 10);
         });
    }
     
    async function compute() {
         var x = await getSomething();
         alert(x * 2);
    }
    compute();
</script>


    

weijie
164 声望7 粉丝