Reputation: 141
I´m trying to traverse dates from a given start date. I'm stuck with the eternal problem around nodeJS and async programming:
getdates('2018-08-01', function(result) {
console.log(result);
})
function getdates (startdate, callback) {
let now = new Date();
let start = new Date(startdate);
let Dates = [];
do {
Dates.push(start);
start.setDate(start.getDate() + 1);
}
while(now.getDate() != start.getDate())
callback(Dates);
}
The result of this is:
[ 2018-08-07T00:00:00.000Z, 2018-08-07T00:00:00.000Z, 2018-08-07T00:00:00.000Z, 2018-08-07T00:00:00.000Z, 2018-08-07T00:00:00.000Z, 2018-08-07T00:00:00.000Z ]
An array with only today's date.
I know is because of the nature of NodeJS, but how can I solve this or do it the right way?
Best regards, Christian
Upvotes: 0
Views: 131
Reputation: 23029
This is not related to any Node.js or asynchronous paradigma. The same will happen in Java, C# and most of other languages.
The problem is at this line: Dates.push(start);
.
start
is an object, therefore it holds the reference. By calling "push" you copy the reference into next field in array.
You end up with array filled with references to the same object, therefore all of them have the same value - the last one you have set to that object.
This will work correctly
getdates('2018-08-01', function(result) {
console.log(result);
})
function getdates (startdate, callback) {
let now = new Date();
let start = new Date(startdate);
let Dates = [];
do {
Dates.push(new Date(start));
start.setDate(start.getDate() + 1);
}
while(now.getDate() != start.getDate())
callback(Dates);
}
Also callbacks are not used anymore (if not necessary), it only makes your code less readable and its much harder to debug.
You can just return the value -
const dates = getdates('2018-08-01');
console.log(dates);
function getdates (startdate, callback) {
let now = new Date();
let start = new Date(startdate);
let Dates = [];
do {
Dates.push(new Date(start));
start.setDate(start.getDate() + 1);
}
while(now.getDate() != start.getDate())
return Dates;
}
Upvotes: 1
Reputation: 12542
It has nothing to do with async programming and it is I don't atleast think 'eternal'.
You are creating 1 date object and pushing it. So the array items are reference to the same object.
here is maybe a crude way to do this:
getdates('2018-08-01', function(result) {
console.log(result);
})
function getdates (startdate, callback) {
const now = new Date();
const start = new Date(startdate);
let Dates = [];
for(let i=0;i<(now.getDate() - start.getDate());i++ ){
const d = new Date(startdate);
d.setDate(d.getDate() + i);
Dates.push(d);
}
callback(Dates);
}
Upvotes: 1