Home > Net >  Javascript to get the previous working day. Returns undefined
Javascript to get the previous working day. Returns undefined

Time:09-25

Been knocking my head for a few hours searching for a solution. Why would prevDate return undefined? Just don't understand what I am missing.

async function prevDate(date) {
    date.setDate(date.getDate()-1)
    if (date.getDay() == 0 || date.getDay() == 6) {
        prevDate(date)
    } else {
        console.log("date: ", date, "day: ", date.getDay())
        return (date)
    }
}

date = new Date("2021-09-20T00:00:00")
prevDate(date)
.then((res) => {
    console.log("res: ", res) //undefined
})
.catch((err) => {
    console.log(err)
})

output
date:  2021-09-17T04:00:00.000Z day:  5
res:  undefined

CodePudding user response:

There is no return statement on line 4.

CodePudding user response:

The other people stated the reason your code doesn't work. But I'm wondering why you are using an async function for code that is not asynchronous. If you still want to use a recursive function it can be simply written like this:

function prevDate (date) {
  date.setDate(date.getDate() - 1);
  
  if (!(date.getDay() % 6)) {
    return prevDate(date);
  } else {
    console.log(`date: ${date} day: ${date.getDay()}`);
    return date;
  }
}

const date = new Date("2021-09-20T00:00:00");
console.log(`res: ${prevDate(date)}`);

Or you can simplify it even further:

const prevDate = (date) => {
  date.setDate(date.getDate() - 1);
  return !(date.getDay() % 6) ? prevDate(date) : date;
};

const date = new Date("2021-09-20T00:00:00");
console.log(`res: ${prevDate(date)}`);

  • Related