如何使用Node.js中异步函数返回的数据? [英] How to use data returned by an asynchronous function in Node.js?
问题描述
我想定义一个函数,它从GET请求的响应中获取某些ID的列表:
I want to define a function that gets me a list of certain IDs from a response of a GET request:
var getList = function (){
var list = [];
https.get(options).on('response', function (response) {
var body = '';
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function () {
var obj = JSON.parse(body);
for (i=0 ; i<obj.length ; i++){
list.push(obj[i].id);
}
//console.log(list);
//return list;
});
});
};
现在,我想在其他功能中使用此功能的列表,或者只是将其分配给一个变量。我明白,因为函数是异步的(好吧, https.get
一个),返回列表并不意味着其他代码不会等待这个函数完。我是否必须将所有剩余的代码放在 response.end
调用中?我知道我在这里遗漏了一些非常明显的东西......
Now, I'd like to use that list from this function in other functions or simply assign it to a variable. I understand that since the function is asynchronous (well, the https.get
one), returning the list won't mean much as the other code will not wait for this function to finish. Do I have to put all the remaining code inside the response.end
call? I know I'm missing something very obvious here...
推荐答案
你可以接受一个回调作为参数并调用它response.end处理程序中的相关数据:
You can accept a callback as a parameter and call it with the relevant data inside the response.end handler:
var getList = function (successCallback){
var list = [];
https.get(options).on('response', function (response) {
var body = '';
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function () {
var obj = JSON.parse(body);
for (i=0 ; i<obj.length ; i++){
list.push(obj[i].id);
}
// invoke the callback and pass the data
successCallback(list);
});
});
};
然后你可以调用 getList
函数和传递回调:
Then you can call the getList
function and pass in a callback:
getList(function(data) {
// do some stuff with 'data'
});
当然其他选项是使用一些实现承诺模式以避免回调地狱。
Of course other options are to use some library implementing the Promises pattern to avoid callback hell.
这篇关于如何使用Node.js中异步函数返回的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!