Reputation: 8970
I have created a small function which checks a list of tags i submit to it and puts the good ones in a good array and the bad ones in the bad array.
This is all done within a callback so once that has been completed, the rest of my code can move on.
I am a little confused on how to access the data in my original function from the callback.
function findTags() {
validateTags(tags, function () {
//How do I access the bad array here?
console.log('These tags are bad ' + badArray.join(','))
});
}
//This will validate the tags submitted and strip out anything bad from them.
//We will return either success if everything is good or an array of the bad tags to fix.
function validateTags(tags, callback) {
var badArray = new Array(),
goodArray = new Array();
tags = tags.split(',');
for (var i = 0; i < tags.length; i++) {
//If the tag contains just alphanumeric, add it to the final array.
if (tags[i].match(/^[a-z0-9\s]+$/i)) {
goodArray.push(tags[i]);
} else {
//Since we didnt match an alphanumeric, add it to the bad array.
badArray.push(tags[i]);
}
}
//console.log(badArray);
//console.log(goodArray);
if (callback) {
callback(badArray);
}
}
Upvotes: 3
Views: 125
Reputation: 29166
Simple. Just use a parameter in your callback definition -
validateTags(tags, function (badArray) {
//How do I access the bad array here?
console.log('These tags are bad ' + badArray.join(','))
});
In your validate tag definition, you are passing your badArray
as an argument to your callback
call. So, simply define a parameter to your callback definition, it will catch your array as its value.
Upvotes: 2