【问题标题】:Return the value of a function Node.js [duplicate]返回函数Node.js的值[重复]
【发布时间】:2016-12-10 09:05:33
【问题描述】:

我有一个从网页读取数据并将其发布到控制台的函数,但我想返回我读过的数据并用它做一些别的事情。所以而不是 console.log(temperature)我想返回温度值并执行 console.log(download(url)) 但它发布了“未定义”。

//require https module
var https=require("https");
//require cheerio to use jquery-like and return a DOM tree
var cheerio=require('cheerio');
var global="";
//a function with url and callback par which connects to URL API and read the data
module.exports.download=function(url){
  //read the data\
  https.get(url,function(res){
    var data="";
    //add it to the data string
    res.on('data',function(chunk){
      data+=chunk;
    });
    //parse it with a callback function
    res.on('end',function(){
      var $=cheerio.load(data);
      var temperature=$("span.temp.swip").text();
     console.log(temperature);
    });
  }).on('error',function(err){
    console.log(err.message)
  });
}

//chose the url to connect
var Ploiesti='44.9417,26.0237';
var Brasov='45.597,25.5525';
var url='https://darksky.net/forecast/' + Ploiesti + '/si24/en';

//download(url);

【问题讨论】:

  • 你必须在 res.on('end') 回调中这样做
  • 这就是我所做的,而不是 console.log(temperature) 我确实返回了温度,最后我做了 console.log(download(url)) 并打印了 undifined
  • 这类问题已经被问了数百次。您必须学习如何在 Javascript 中使用异步结果进行编程。上面的副本为您提供了许多选择。

标签: javascript node.js express return cheerio


【解决方案1】:

所以你需要一个回调来将变量分配给它并从任何地方获取,看看cb

var download = function(url, cb){
  //read the data\
  https.get(url,function(res){
    var data="";
    //add it to the data string
    res.on('data',function(chunk){
      data+=chunk;
    });
    //parse it with a callback function
    res.on('end',function(){
      var $=cheerio.load(data);
      var temperature=$("span.temp.swip").text();
      cb(temperature);
    });
  }).on('error',function(err){
    console.log(err.message)
  });
}

module.exports.download = download;

那么如果你需要从web调用函数你需要一个路由,使用Express并将之前的文件保存为download.js

var express = require('express'),
    app = express(),
    download = require('download.js');

app.get('/temperature', function (req, res) {
  // Get the temp
  var Ploiesti='44.9417,26.0237',
      Brasov='45.597,25.5525',
      url='https://darksky.net/forecast/' + Ploiesti + '/si24/en';

  download.download(url, function (temp) {
     // Send the response to the web
     res.json({ temperature: temp);
  });
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
});

【讨论】:

  • 除了您的代码外,好的答案还应包含有关您如何解决 OP 问题的文字说明。这个答案没有提供任何解释,现在需要有人在您的代码和 OP 的代码之间进行视觉差异,以试图找出您所做的更改。
  • 是的,我已经这样做了,它可以工作,但我不想在控制台上发布温度我想将它保存到变量或对象中,然后将其传递并发布到网页,所以我需要从该函数中提取变量温度
  • 如果您在网页中需要它,您需要为 node.js 建立一个路由并从网络调用下载函数。然后您可以用温度响应呼叫。看看 Express 做这个expressjs.com/en/starter/hello-world.html
  • 请查看已编辑的答案,我添加了您需要的所有内容。
猜你喜欢
  • 2016-08-14
  • 2014-06-13
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
  • 2016-01-03
  • 2014-02-03
  • 2016-08-08
  • 2021-07-02
相关资源
最近更新 更多