app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
var koa       = require('koa');
var app       = koa();
var unirest   = require('unirest');
var thunkify  = require('thunkify');


// Use thunkify to wrap custom async function.
var get1 = thunkify(function(callback) {
  unirest.get('http://www.baidu.com')
  .end(function(response) {
    callback(null, response);
  })
});

// "thunkify" simple version.
var get2 = function() {

  return function(done){

    try {
      unirest.get('http://www.baidu.com')
        .end(function(response) {

          done(null, response)
      })
    } catch (err) {
      done(err);
    }
  }
}

// Exception demo.
var geterror = thunkify(function(callback) {

  unirest.get('http://www.baidu.com')
    .end(function(response) {

      // throw new Error('uncaughtErrorTest') // This exception can't be caught by generator.
      callback(new Error('uncaughtErrorTest'))
  })
})

// Simple router.
app.use(function *(){
  var response;
  try {
    if (this.path === '/get1') {
      console.log('get1')
      response = yield get1();
      this.body = response.body;

    } else if (this.path === '/get2') {
      console.log('get2')
      response = yield get2();
      this.body = response.body;

    } else if (this.path === '/geterror') {
      console.log('geterror')
      this.status = 500;
      response = yield geterror()
      this.body = response.body;

    } else {
      console.log(this.path)
      this.body = '<a href="/get1">get1</a><br><a href="/get2">get2</a><br><a href="/geterror">geterror</a>'
    }
  } catch (e) {
    console.log(e)
    this.body = e.stack;
  }
});


app.listen(3000);
console.log('\r\nVisit localhost:3000 to debug it.')

package.json

{
  "name": "test-koa",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "koa": "^1.1.2",
    "thunkify": "^2.1.2",
    "unirest": "^0.4.2"
  }
}