2017-09-08 40 views
0

,直到我的函数结束,我不能达到我值之前,导致..我试过的回调,但它似乎没有工作..获取功能节点的结束

exports.helloHttp = function helloHttp (req, res) { 
    var url = "https://api.coindesk.com/v1/bpi/currentprice.json"; 
    var btcValue 
    require('https').get(url, function(res, btcValue){ 
     var body = ''; 

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

     res.on('end', function(){ 
      btcValue = JSON.parse(body); 
      callback(btcValue); 
     }); 
     }).on('error', function(e){ 
      console.log("Got an error: ", e); 
     }); 
    console.log("Got a respons ", btcValue); 
    res.setHeader('Content-Type', 'application/json'); 
    res.send(JSON.stringify({ "speech": response, "displayText": response 
    })); 
}; 

感谢很多提前

+0

'callback'在哪里?你只是调用回调,但它在哪里?上面的代码应该抛出错误'未定义回调“ – Subburaj

回答

0

我根据你的代码写了一个独立的例子:

var http = require('http'), 
    https = require('https'); 

http.createServer(function(req, res) { 
    // You can largely ignore the code above this line, it's 
    // effectively the same as yours but changed to a standalone 
    // example. The important thing is we're in a function with 
    // arguments called req and res. 
    var url = 'https://api.coindesk.com/v1/bpi/currentprice.json'; 

    var request = https.get(url, function(response) { 
     var body = ''; 

     response.on('data', function(chunk) { 
      body += chunk; 
     }); 

     response.on('end', function() { 
      // TODO: handle JSON parsing errors 
      var btcValue = JSON.parse(body); 

      res.setHeader('Content-Type', 'application/json'); 

      res.end(JSON.stringify({ 
       btcValue: btcValue 
      })); 
     }); 
    }); 

    request.on('error', function(e) { 
     console.error(e); 
    }); 

    // Runs this example on port 8000 
}).listen(8000); 

最重要的变化是移动的代码来处理我们的响应(res)到'end'听众的coindesk响应。对硬币台的呼叫是异步的,因此我们必须等待'end'事件,然后再尝试采取行动。

构建JSON时,引用一个名为response的变量两次。您的代码没有定义response,但我认为它应该与拨号到coindesk的btcValue相关。我不确定你到底想要什么,所以我只是将btcValue包装在另一个对象中用于演示目的。

在你原来的代码,你有这样一行:

require('https').get(url, function(res, btcValue){ 

这第二个参数,您呼叫btcValue,不存在,因此它只会被设置为undefined

我已将send更改为end但这不是重大更改。我假设你使用Express(它提供了一个send方法),而我的例子不是。