Problem with return value of function

For a script I need to get the current date and the format it to a full hour. I made a very basic script with a function that takes the hour as a parameter, gets the current date/time, sets the hour on the value of the parameter and the other timedata to 0 and then return the date. I guess a make a beginner mistake here, because it is not working. It seems that the function is not returning anything (console.log of the variable is empty). If I don’t use a function to format the date, it works flawlessly. However I need to format multiple variables in the script, so using a function would make it Much cleaner,

Can someone tell me what I am doing wrong?

const formatted = formatTime(12)


async function formatTime(hours) {
  let date = new Date()
  return date

Well, you could get rid of the async. This doesn’t look like an asynchronous function to me. Also, you can call setHours with all four time parameters instead of doing minutes, seconds and milliseconds individually.

When I try this, it works as expected:

const t = formatTime(12);

function formatTime(hours) {
	let date = new Date();
	date.setHours(hours, 0, 0, 0);
	return date;
1 Like

Thanks that works. I have to make myself familiar with „async“ functions. I got the base of my script from the gallery and every function had „async“ before the name.

Generally, you only need async if there is any await inside it. Even if you return the call to another function, which is async or returns a promise, then you also don’t need it.

function normalFunc() {
  return "Hello world";
// no await needed because it isn't async and doesn't return a Promise

async function asyncFunc() {
  return 42;
// here we need await because it is async
log(await asyncFunction());

function returnsPromise() {
  return Promise.resolve("foo");
// needs await because it returns a Promise (if you want the value from the Promise. This is usually the case)
log(await returnsPromise());

async function asyncReturnsPromise() {
  // you don't need await here
  return Promise.resolve("hi");
// ... because the Promise is unpacked recursively
log(await asyncReturnsPromise());

log() is a global function that calls console.log().


Thank you for the detailed explanation. That was very helpful.