从Node.js中的回调函数返回一个值 [英] Returning a value from callback function in Node.js
问题描述
我在Node.js中从回调函数返回一个值时遇到小问题,我将尽可能简单地解释我的情况。考虑我有一个片段,它接受URL并点击该url并给出输出:
I am facing small trouble in returning a value from callback function in Node.js, I will try to explain my situation as easy as possible. Consider I have a snippet, which takes URL and hits that url and gives the output:
urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
});
我试图将其包装在函数中并返回如下值:
I tried to wrap it inside a function and return a value like this:
function doCall(urlToCall) {
urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return finalData;
});
}
因为在我的Node.js代码中,我有很多 if-else
将决定 urlToCall
的值的声明,如下所示:
Because in my Node.js code, I have a lot of if-else
statement where value of urlToCall
will be decided, like this:
if(//somecondition) {
urlToCall = //Url1;
} else if(//someother condition) {
urlToCall = //Url2;
} else {
urlToCall = //Url3;
}
事情是 urllib中的所有语句.request
将保持不变,但 urlToCall
的值除外。所以我肯定需要将这些公共代码放在函数中。我试过同样的但是在 doCall
总是会给我 undefined
。我试过这样:
The thing is all of the statements inside a urllib.request
will remain same, except value of urlToCall
. So definitely I need to put those common code inside a function. I tried the same but in doCall
will always return me undefined
. I tried like this:
response = doCall(urlToCall);
console.log(response) //Prints undefined
但是如果我在里面打印值 doCall()
它打印完美,但它总会返回 undefined
。根据我的研究,我发现我们无法从回调函数返回值! (是真的吗?)如果是的话,任何人都可以建议我如何处理这种情况,因为我想在每个 if-else
块中防止重复代码。
But if I print value inside doCall()
it prints perfectly, but it will always return undefined
. As per my research I came to know that we cannot return values from callback functions! (is it true)? If yes, can anyone advice me how to handle this situation, as I want to prevent duplicate code in every if-else
blocks.
推荐答案
其未定义
因为, console.log(响应)
在 doCall(urlToCall);
之前运行。您还必须传入一个回调函数,该函数在您的请求完成时运行。
Its undefined
because, console.log(response)
runs before doCall(urlToCall);
is finished. You have to pass in a callback function aswell, that runs when your request is done.
首先,您的函数。传递回调:
First, your function. Pass it a callback:
function doCall(urlToCall, callback) {
urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return callback(finalData);
});
}
现在:
var urlToCall = "http://myUrlToCall";
doCall(urlToCall, function(response){
// Here you have access to your variable
console.log(response);
})
@Rodrigo,发布了好资源。阅读节点中的回调以及它们的工作原理。请记住,它是异步代码。
@Rodrigo, posted a good resource in the comments. Read about callbacks in node and how they work. Remember, it is asynchronous code.
这篇关于从Node.js中的回调函数返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!