I'm working with an open-source library for processing and parsing genetic data in VCF and Tabix formats. It contains functions and classes that make it easy to read an index file (a Tabix) and load corresponding data from a compressed VCF.
It works asynchronously (unsurprisingly), however, and I'm not sure of the best way to structure my code. I'm looking to make multiple calls to the getRecords()
method—since I need to retrieve multiple discontinuous segments of data; because this is asynchronous, it seems like I also have to instantiate a new file reading object (here known as readBinaryVCF
but roughly analogous to HTML's FileReader
). Both the file reading object's constructor and the getRecords()
function use callbacks.
I'm not really experienced in JavaScript or asynchronous design patterns; I'm hoping it doesn't have to be this convoluted. Other solutions that I tried, though, like recursing or making multiple calls to getRecords()
on the same object, were not as flexible or as robust—or just flat out didn't work.
The code sample below is the first iteration I've gotten to work. That being said, please tear it apart. I suspect there're many improvements to be made.
EDIT: I'll leave this code alone as my first draft, but please look at the minor changes I've made in an answer below. I'm still hoping for help, preferably on top of my revisions.
var regions = [
[10, 10000, 100000],
[12, 10000, 100000],
[14, 10000, 100000],
[18, 10000, 100000]
];
var d = [];
var readers = [];
for (var a = 0; a < regions.length; a++) {
d.push([]);
readers.push(new readBinaryVCF(tabix, vcf, function(x) {x = x;}));
//Should I just initialize these to null instead?
}
regions.forEach(function(item, i) {
readers[i] = new readBinaryVCF(tabix, vcf, function(tabixReader) {
rbvcf = readers[i];
var index = 0;
for (key in tabixReader.idxContent.namehash) {
if (key == regions[i][0]) {
index = tabixReader.idxContent.namehash[key];
}
}
rbvcf.getRecords(index, regions[i][1], regions[i][2], function(data) {
d[i] = data;
if (i == regions.length - 1) {
var finalText = "";
for (var j = 0; j < d.length; j++) {
for (var k = 0; k < d[j].length; k++) {
finalText = finalText + d[j][k] + "<br />";
}
}
$(".text").html(finalText);
}
});
});
});