问题
I am trying to get data from my persistencejs(this is a library!) database in javascript. I am getting the values and pushing them in the array, I'm doing this in a forEach loop. In the loop the array is being filled with values, I have confirmed this using alerts.
But when I look at the array outside of the loop, it's empty. Why is this?
Here's the code (I've tried putting the variable inside the function, and tried changing it to this.newDataArray as well.):
var newDataArray = new Array();
function getData(){
dataTable.all().list(function(tasks){
tasks.forEach(function (r) {
var tTank1 = r.Tank1;
var tTank2 = r.Tank2;
var tTank3 = r.Tank3;
var tTank4 = r.Tank4;
var tHelicopter = r.Helicopter;
newDataArray.push(tTank1, tTank2, tTank3, tTank4, tHelicopter);
alert(newDataArray);
});
});
alert(newDataArray);
return newDataArray
}
Here I am just testing the return value in a method that's being executed:
Data.prototype.fetchData = function(csv){
jQuery.get(csv, function(data) {
var result = $.csv.toArrays(data);
result.shift();
result.forEach(function (r) {
var joinedResult = r.join();
fillDB(joinedResult);
});
});
alert(getData());
};
So I'm hoping anyone knows the answer to this? Also other criticism about my code and/or post format are welcome as well :)
回答1:
The problem is probably not that the data isn't being populated, but that you're alerting it too soon.
jQuery's get is an asynchronous call, and it returns before the callback has processed. If you move the alert inside the get call, you should have your data.
Data.prototype.fetchData = function(csv){
jQuery.get(csv, function(data) {
var result = $.csv.toArrays(data);
result.shift();
result.forEach(function (r) {
var joinedResult = r.join();
fillDB(joinedResult);
});
alert(getData());
});
};
来源:https://stackoverflow.com/questions/17992837/array-refuses-to-be-returned-with-values