<script>
function getSomething(cb){
var r =0;setTimeout(function(){
r =2;cb(r);},100);}
function compute(x){alert(x *2);}getSomething(compute);</script>
promise方法
function getSomething(){
var r =0;returnnewPromise(function(resolve){setTimeout(function(){
r =2;resolve(r);},10);});}
function compute(x){alert(x *2);}getSomething().then(compute);
generator
functiongetSomething(){var r =0;setTimeout(function(){
r =2;
it.next(r);},10);}function*compute(it){var x =yieldgetSomething();alert(x *2);}var it =compute();
it.next();
promise + generator
functiongetSomething(){var r =0;returnnewPromise(function(resolve){setTimeout(function(){
r =2;resolve(r);},10);});}function*compute(){var x =yieldgetSomething();alert(x *2);}var it =compute();
it.next().value.then(function(value){
it.next(value);});
ES7 - 终极方案
<script type="text/javascript">functiongetSomething(){var r =0;returnnewPromise(function(resolve){setTimeout(function(){
r =2;resolve(r);},10);});}asyncfunctioncompute(){var x =awaitgetSomething();alert(x *2);}// 直接调用compute()方法 -> x为同步请求返回结果,输出4compute();// 表示getSomething获取返回值后执行resolve状态 -> // 当.then()前的方法执行完后再执行then()内部的程序,这样就避免了,数据没获取到等的问题getSomething().then(compute);</script>