即使在'end'事件上指定return,NodeJS http.request也不返回数据 [英] NodeJS http.request not returning data even after specifying return on the 'end' event
问题描述
基本上我试图从网站上删除一些数据并在绑定到 http.request
的'end'事件的回调函数上执行DOM提取,删除和更新。
Basically I am trying to scrap some data from website and perform the DOM extraction, deletion and updation on a callback function binded to the 'end' event of http.request
.
我已经从'end'
事件回调中返回了数据但是我的路线中没有收到回调函数。我得到 undefined
那里。
I have returned the data from the 'end'
event callback too but it is not receiving in my route callback function. I get undefined
there.
下面是代码块:
var scraper = {
extractEmail: function (directoryName) {
var result = getDirectory(directoryName);
if (result !== 404) {
var protocol = result.https ? https : http;
protocol.request({
host: 'somevalue.net',
method: "GET"
}, function (res) {
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
return data;
});
})
.on('error', function (err) {
return err;
})
.end();
//return data;
}
else {
//return "Failed";
}
}
};
这是Routes.js函数:
And here is the Routes.js function:
app.get('/:directory', function (req, res) {
var n = scraper.extractEmail(req.params.directory);
console.log(n);
res.send(n);
});
在这里我也没有得到 n $的值c $ c>。
推荐答案
您无法从异步回调中返回值。嗯,你可以,但它很可能会被忽略,而且肯定不会做你想要的。
You cannot return a value from an asynchronous callback. Well, you can, but it most likely will get ignored and most certainly won't do what you want.
你甚至不能在那个地方回复承诺。您只能解决现在使用return语句的promise。您需要从main函数返回一个promise,然后在现在使用return的事件处理程序中解析或拒绝promise。
You cannot even return a promise in that place. You can only resolve a promise where you now use the return statements. You need to return a promise from the main function and then resolve or reject the promise in your event handlers where you use returns now.
有关详细信息,请参阅以下答案:
For more info see those answers:
- Return Promise result instead of Promise in Nodejs
- Return value in function from a promise block
- jQuery: Return data after ajax call success
这篇关于即使在'end'事件上指定return,NodeJS http.request也不返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!