Reputation: 159
I have this function. But how can I get data from my 2 txt file functions? I want to have the tho Tabt values out in my alerts.
function getWeight(){
var fileKevin = "https://dl.dropboxusercontent.com/s/mytextfile1.txt";
var fileHeidi = "https://dl.dropboxusercontent.com/s/mytextfile1.txt";
//GET DATA FOR KEVIN
$.get(fileKevin,function(txt){
var lines = txt.split("\n");
var total = parseInt(lines.length)
var first = parseInt(0)
var last = parseInt(total-1)
var prev = parseInt(total-2)
var NuVaegt = (splitWeight(lines[last],1))
var StartVaegt = splitWeight(lines[first],1);
var ForrigeVaegt = splitWeight(lines[prev],1)
var Tabt = decimal((NuVaegt-StartVaegt),1)
var Sidst = decimal((NuVaegt-ForrigeVaegt),1)
return Tabt;
});
//GET DATA FOR HEIDI
$.get(fileHeidi,function(txt){
var lines = txt.split("\n");
var total = parseInt(lines.length)
var first = parseInt(0)
var last = parseInt(total-1)
var prev = parseInt(total-2)
var NuVaegt = (splitWeight(lines[last],1))
var StartVaegt = splitWeight(lines[first],1);
var ForrigeVaegt = splitWeight(lines[prev],1)
var Tabt = decimal((NuVaegt-StartVaegt),1)
var Sidst = decimal((NuVaegt-ForrigeVaegt),1)
return Tabt;
});
alert(Tabt) //function Kevin
alert(Tabt) //function Heidi
};//end getWeight
can you help me?
Please ignore this: adding text adding text
adding text
adding text
Upvotes: 0
Views: 47
Reputation: 3407
you can't return data from an asynchronous function such as $.get
, you have to use callbacks.
What you get back is deferred or promise objects which you can group like this:
var call1 = $.get(fileKevin...
var call2 = $.get(fileHeidi...
$.when( call1, call2 ).done(function ( txtKevin, txtHeidi ) {
checkout $.when
you should probably refactor since you have duplicated code
example:
function getWeight() {
var fileKevin = "https://dl.dropboxusercontent.com/s/mytextfile1.txt";
var fileHeidi = "https://dl.dropboxusercontent.com/s/mytextfile1.txt";
$.when(
$.get(fileKevin),
$.get(fileHeidi)
).done(function (txtKevin, txtHeidi) {
var weightKevin = parseWeight(txtKevin),
weightHeidi = parseWeight(txtHeidi);
console.log(weightKevin, weightHeidi);
// here you will call any function that has to use those values like:
// doSomething(weightKevin, weightHeidi);
});
function parseWeight(txt) {
var lines = txt.split("\n");
var total = parseInt(lines.length)
var first = parseInt(0)
var last = parseInt(total-1)
var prev = parseInt(total-2)
var NuVaegt = (splitWeight(lines[last],1))
var StartVaegt = splitWeight(lines[first],1);
var ForrigeVaegt = splitWeight(lines[prev],1)
var Tabt = decimal((NuVaegt-StartVaegt),1)
var Sidst = decimal((NuVaegt-ForrigeVaegt),1)
return Tabt;
}
};
Upvotes: 2