Skip to content
Exercise · Asynchronous code · lesson 12 of 12

Exercise: a promise with a time limit

Write a function function withTimeout(promise, ms, fallback) that returns a new promise. If promise is fulfilled before ms milliseconds pass, the new promise is fulfilled with the same value; if promise is rejected first, the new promise is rejected with the same error. If neither happens within ms milliseconds, the new promise is fulfilled with fallback.

In the tests, after(ms, value) is a promise that is fulfilled with value after ms milliseconds, and failAfter(ms, message) is rejected with the error message after ms milliseconds.

  • withTimeout(after(10, "data"), 40, "late") → "data"
  • withTimeout(after(40, "data"), 10, "late") → "late"
  • withTimeout(failAfter(10, "boom"), 40, "late") → rejected with the error boom

Constraints: ms is an integer from 10 to 50; fallback is returned as is, even when it is 0; a rejection that comes later than ms milliseconds no longer matters.

Do not add extra imports unless the task says so explicitly.

with-timeout.js — javascript
javascript · 4 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way