【发布时间】: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