LearnFrenzy
Sign in Take a free test

Async/Await · Async/Await Coding Problems · Question 3

Give an awaited call a time limit in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Write timeout(promise, ms, label) for use with await: it resolves with the promise's value or throws "label timed out after ms ms", and always clears its timer.

Solution
main.js
async function timeout(promise, ms, label) {
  let timer;
  try {
    return await Promise.race([
      promise,
      new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms} ms`)), ms); }),
    ]);
  } finally {
    clearTimeout(timer);
  }
}

const query = (ms, rows) => new Promise((r) => setTimeout(() => r(rows), ms));
(async () => {
  for (const [label, ms] of [["fast query", 5], ["slow query", 40]]) {
    try {
      console.log(label, "→", await timeout(query(ms, 12), 20, label), "rows");
    } catch (e) {
      console.log(e.message);
    }
  }
})();

Output Verified by running it on Node.js

fast query → 12 rows
slow query timed out after 20 ms

return await inside try lets finally clear the timer in every case, so a fast result does not leave a timer running.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links