您当前的位置: 首页 > 
  • 2浏览

    0关注

    483博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

新手如何玩co.generator

高精度计算机视觉 发布时间:2017-11-19 16:03:40 ,浏览量:2

新手如何玩co.generator

这是一个最简单如何入手的例了,同系列类似的还有mocha, mocha-co, co-mocha,写给新手看的。

1.首先建立一个test文件夹,该文件夹下建立一个main.js

2.命令窗口下切换到test目录,安装(我是全局安装,所以有个后缀-g)

先建立一个package.json

npm init

一路回车选默认值即可。

npm install co -g

如果想把安装保存到package.json,在后面加上–save即可,如下

npm install co --save

当然,如果你只学习简内容,上面这个安装就够了,我正好比较懒,嫌麻烦,就一发把所有相关测试的东东全装上,如下

npm install co -g
npm install mocha -g
npm install thunkify -g
npm install mocha-co -g 
npm install co-mocha -g 

3.打开main.js,输入以下内容

var co =require("co");
function sayHello(userName){
    return function(callback)
    {
        setTimeout(function () {
            callback(null,"hello "+userName);
        },2000)
    }
}
co(function *(){
    var a = yield sayHello("a");
    console.log(a);
    var b = yield sayHello("b");
    console.log(b);

   yield function * (){
       var a = yield sayHello("c");
       console.log(a);
       var b = yield sayHello("d");
       console.log(b);
   };
}).catch(function(err){
    console.log(err.stack);
})

4.在命令窗口中输入

node main.js

每隔2秒,窗口会依次输出:

hello a
hello b
hello c
hello d

5.再来看一个官方(https://github.com/tj/co)的例子,把main.js中的内容写成以下

var co = require('co');

co(function *(){
  // yield any promise
  var result = yield Promise.resolve(true);
}).catch(onerror);

co(function *(){
  // resolve multiple promises in parallel
  var a = Promise.resolve(1);
  var b = Promise.resolve(2);
  var c = Promise.resolve(3);
  var res = yield [a, b, c];
  console.log(res);
  // => [1, 2, 3]
}).catch(onerror);

// errors can be try/catched
co(function *(){
  try {
    yield Promise.reject(new Error('boom'));
  } catch (err) {
    console.error(err.message); // "boom"
 }
}).catch(onerror);

function onerror(err) {
  // log any uncaught errors
  // co will not throw any errors you do not handle!!!
  // HANDLE ALL YOUR ERRORS!!!
  console.error(err.stack);
}

在命令窗口中输入

node main.js

窗口会依次输出

boom
[ 1, 2, 3 ]

注意,例如,如果你碰到Error: Cannot find module ‘thunkify’,一般是因为路径的原因,这时你检查一下,第一,有没有安装thunkfify(npm install thunkify),第二,前面有没有生成package.json文件,第三,在main.js中有没有导入使用thunkify ( var thunkify = require(‘thunkify’); ). npm全局安装e之后,最好注销重新启动一下,这样node才能找到新路径。有时你全局安装了也不行,这时你就老老实实在当前目录下再装一次。比如

npm install thunkify

唉,windows下经常有这种奇葩的问题。

更高大上的内容请参考资料:

1.https://github.com/tj/co

2.https://github.com/mochajs/mocha

3.https://www.cnblogs.com/wangfupeng1988/p/6532713.html

4.and so on

关注
打赏
1661664439
查看更多评论
立即登录/注册

微信扫码登录

0.0404s