原创声明:本文为作者原创,未经允许不得转载,经授权转载需注明作者和出处
本文主要有关系的是co模块
无论是前端还是后端,对于异步回调都很了解熟悉,浏览器中的各种交互逻辑都是通过事件回调实现的,前端逻辑越来越复杂,导致回调函数越来越多。
有的时候,由于我们业务的需要,我们必须得使用过多的回调函数嵌套
$.post('/app/user', function(data) { 
  console.log(data); 
  $.post('/app/banks',{''userId":"data.userId''}, function(result) {
       console.log(result); 
        $.post('/app/money',{''cardNo":"result.cardNo''}, function(res) { 
            console.log(res.howMuchMoney) 
      }); 
    });
  });
function co(gen) {
 var ctx= gen(); 
 var ret = ctx.next();
 ret.value.then(function(res) {
 ctx.next(res); 
  });
}
首先生成一个迭代器,然后执行一遍 next(),得到的 value 是一个 Promise 对象,Promise.then() 里面再执行 next()。当然这只是一个原理性的演示,很多错误处理和循环调用 next() 的逻辑都没有写出来。
传统模式:hahahello是一个异步函数
function hahahello() { 
return Promise.resolve('hello').then(function(hello) { 
  console.log(hello); 
});
}
function helloworld() { 
  hahahello();
  console.log('world');
}
helloworld();
输出
    "world"
    "hello"
co 模块:
function co(gen) { 
var ctx= gen(); 
var ret = ctx.next(); 
ret.value.then(function(res) { 
  ctx.next(res);
 });
}
function hahahello() { 
return Promise.resolve('hello').then(function(hello) { 
console.log(hello); 
});
}
co(function *helloworld() { 
yield hahahello(); 
console.log('world');
});
此时输出
"hello"
"world"
var co = require('co');
co(function *() { 
  yield sayI(); 
  yield sayLove(); 
  yield sayYou();
  yield sayXiaohuangxiang();
});
打印出:
I 
Love 
You
Xiaohuangxiang
根据meikidd文章学习心得