简体   繁体   English

永远不会调用模块中的Node.js回调

[英]Node.js callbacks in module are never called

My problem actually is that I was using the response body before the callback was called, which resulted in an error and therefore the callback was never called. 我的问题实际上是我在调用回调之前就使用了响应主体,这导致了错误,因此从未调用过该回调。

I am using request module , though this problem seems to happen with any callback. 我正在使用request模块 ,尽管此问题似乎发生在任何回调中。

If I do something like this. 如果我做这样的事情。

var request = require('request');

module.exports.test = function ()
{
    request('http://www.google.com', function (error, response, body) {
        /**
         * This callback doesn't seem to ever be called.
         */

        console.log(body);
    });
};

And use it like. 并像使用它。

var mytest = require('./test.js');

mytest.test();

The callback doesn't seem to ever be called. 回调似乎从未被调用过。

Your code is working as expected and if you don't see any output that means some error had place which should be indicated in error argument passed to your function. 您的代码按预期工作,并且如果没有看到任何输出,则表明存在error ,应在传递给函数的error参数中指示该error

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Print the google web page.
  } else {
    console.log('error: '+ response.statusCode)
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM