222
schangxiang@126.com
2025-06-13 6a8393408d8cefcea02b7a598967de8dc1e565c2
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
 
var thunkify = require('..');
var assert = require('assert');
var fs = require('fs');
 
describe('thunkify(fn)', function(){
  it('should work when sync', function(done){
    function read(file, fn) {
      fn(null, 'file: ' + file);
    }
 
    read = thunkify(read);
 
    read('foo.txt')(function(err, res){
      assert(!err);
      assert('file: foo.txt' == res);
      done();
    });
  })
 
  it('should work when async', function(done){
    function read(file, fn) {
      setTimeout(function(){
        fn(null, 'file: ' + file);
      }, 5);
    }
 
    read = thunkify(read);
 
    read('foo.txt')(function(err, res){
      assert(!err);
      assert('file: foo.txt' == res);
      done();
    });
  })
 
  it('should maintain the receiver', function(done){
    function load(fn) {
      fn(null, this.name);
    }
 
    var user = {
      name: 'tobi',
      load: thunkify(load)
    };
 
    user.load()(function(err, name){
      if (err) return done(err);
      assert('tobi' == name);
      done();
    });
  })
 
  it('should catch errors', function(done){
    function load(fn) {
      throw new Error('boom');
    }
 
    load = thunkify(load);
 
    load()(function(err){
      assert(err);
      assert('boom' == err.message);
      done();
    });
  })
 
  it('should ignore multiple callbacks', function(done){
    function load(fn) {
      fn(null, 1);
      fn(null, 2);
      fn(null, 3);
    }
 
    load = thunkify(load);
 
    load()(done);
  })
 
  it('should pass all results', function(done){
    function read(file, fn) {
      setTimeout(function(){
        fn(null, file[0], file[1]);
      }, 5);
    }
 
    read = thunkify(read);
 
    read('foo.txt')(function(err, a, b){
      assert(!err);
      assert('f' == a);
      assert('o' == b);
      done();
    });
  })
 
  it('should work with node methods', function(done){
    fs.readFile = thunkify(fs.readFile);
 
    fs.readFile('package.json')(function(err, buf){
      assert(!err);
      assert(Buffer.isBuffer(buf));
 
      fs.readFile('package.json', 'utf8')(function(err, str){
        assert(!err);
        assert('string' == typeof str);
        done();
      });
    });
  })
})