1

I was asked this question in an interview yesterday, on how to change the code so that it gives the expected output. I got a hint that await can be used before callMe(delay) function.

function callMe(delay) {
    setTimeout(() => {
        console.log('Called');
    }, delay);
}

const delays = [500, 1000, 1500];
for (let delay of delays) {
    callMe(delay);
}
console.log('Completed');

//## Expected Output -
// Called
// Called
// Called
// Completed

This question has been bothering me a lot. Thanks in advance.

Nishant
  • 466
  • 2
  • 15
  • 2
    Does this answer your question? [Combination of async function + await + setTimeout](https://stackoverflow.com/questions/33289726/combination-of-async-function-await-settimeout) – luk2302 Jun 04 '21 at 08:25
  • 1
    not to offend you but attending a JS interview without knowing this is like aaking to drive a car without knowing what is accelarator and break! this can help you get started - https://nodejs.dev/learn after this if you like to do server programming then please considering researching express, mongodb, postgresql etc....also checkout lodash.com and bluebirdjs.com – Nidhin David Jun 04 '21 at 08:59
  • 3
    @Nidhin David not really. I was stuck for a decade below ECMA6 as well since I had to maintain old intranet solutions for banks. I missed out on alot of the new *goodies* as well. Also your recommendations are questionable.. each employer has its own needs. – JavaScript Jun 04 '21 at 09:26
  • @JavaScript can you point to me a referene wherein settimeout executes synchronously in old JS, just curious to update my knowledge? Also you are free to question my recommendation and share yours as well! – Nidhin David Jun 04 '21 at 16:53
  • @Nidhin David Where is that question coming from? I did not imply anything of that sort. However, I am sure you can think of a way to wait for a for loop which has a definite length and use a callback. And no, I do not share subjective recommendations, as you can read in my comment above. – JavaScript Jun 05 '21 at 19:29

1 Answers1

4

Try

function callMe(delay) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("Called");
      // Resolve Promise, when Timeout is over
      resolve();
    }, delay);
  });
}

// Async Main Function
(async () => {
  const delays = [500, 1000, 1500];
  for (let delay of delays) {
    // Await the Timeout with the Promise
    await callMe(delay);
  }
  console.log("Completed");
})();

The callMe function now returns a promise, so that it can get awaited

The main function is now async, as the await can only be used in async functions. The await ensures that the timeout is done and only then it continues.

shaedrich
  • 5,457
  • 3
  • 26
  • 42
Mark
  • 485
  • 7
  • 14
  • Hi @Mark, thank you, please can you explain it in brief – Nishant Jun 04 '21 at 08:33
  • 1
    Yes, so I've made callMe an Promise, which gets resolved, when the timeout is over. The main Part is now async, as I have to await the Promises to get resolved. I am basically awaiting the timeouts and after they get resolved I continue with the next Promise – Mark Jun 04 '21 at 08:37
  • 3
    `callMe()` does not need to be `async` since it returns a promise. – Lain Jun 04 '21 at 09:01