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;
});
});
};
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...
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);
});
});
};
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.
make the list as global or accessible
var list = []
//declare a get method
function getUpdatedList(){
return list;
}
if you call before ajax finish you will get null anfter you will get the actual data array, but in normal cases just uses callback functions like
function getList(callback){
///
//
response.on('end', function () {
var obj = JSON.parse(body);
for (i=0 ; i<obj.length ; i++){
list.push(obj[i].id);
}
callback(list);
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.