如何在Nodejs中使用Q-lib和restify

时间:2014-12-24 09:48:50

标签: node.js asynchronous q restify

你能帮助我如何使用Q,改善图书馆协作吗?

这就是我想要交换的内容。不要使用Q,只是为了解决问题。

  var deffered = Q.defer();

  client.get('/pension/woori_m.asp?pension_code=w0101200', function (err, req) {
    assert.ifError(err);

    req.on('result', function (err, res) {
      assert.ifError(err);

      res.body = '';
      res.on('data', function (chunk) {
        res.body += euckr2utf8.convert(chunk);
        console.log(res.body);
      });

      res.on('end', function() {
        deffered.resolve(res.body);
      });
    });
  });

这就是我用下两件事改变了代码

  function requestTo(path) {
    var deffered = Q.defer();
    client.get(path, function (err, req) {
      if (err) {
        deffered.reject(new Error(err));
      }
      deffered.resolve(req);
    });
  }

  function getResult(request) {
    var deffered = Q.defer();
    request.on('result', function (err, res) {
      deffered.resolve(res);
    });
  }

  function getData(response) {
    var deffered = Q.defer();
    response.body = '';
    response.on('data', function ( chunk) {
      response.body += euckr2utf8.convert(chunk);
      deffered.resolve(response.body);
    });
  }

这是执行代码。

  requestTo('/pension/woori_m.asp?pension_code=w0101200')
    .then(function(request) {
      return getResult(request);
    })
    .then(function(result) {
      getResult(result);
    })
    .then(function(response) {
      getData(response);
    })
    .then(function(data) {
      deffered.resolve(data);
    });

这是调试时的结果。我怎么用这种方式?

> debugger listening on port 55083
> 
> /Users/tourdoc/PhpstormProjects/untitled1/app/test.js:56
>     .then(function(request) {
>      ^ TypeError: Cannot call method 'then' of undefined
>     at getChunks (/Users/tourdoc/PhpstormProjects/untitled1/app/test.js:56:6)
>     at Object.<anonymous> (/Users/tourdoc/PhpstormProjects/untitled1/app/test.js:101:1)
>     at Module._compile (module.js:456:26)
>     at Object.Module._extensions..js (module.js:474:10)
>     at Module.load (module.js:356:32)
>     at Function.Module._load (module.js:312:12)
>     at Module.runMain [as _onTimeout] (module.js:497:10)
>     at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)
> 
> Process finished with exit code 8

1 个答案:

答案 0 :(得分:0)

我运行你的代码,并得到同样的错误:

/tmp/test.js:37
    .then(function(request) {
     ^
TypeError: Cannot call method 'then' of undefined
    at Object.<anonymous> (/tmp/test.js:37:6)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3

然后我在return deffered.promise;requestTogetResult函数的末尾添加getData,这很有效。所以,不要错过任何return,一切都会好的。