Promise with Timeout
MediumP2Coding
Implement withTimeout(promise, ms), which returns a promise that follows promise but gives up after ms milliseconds.
- If
promiseresolves withinms, the result resolves with the same value. - If
promiserejects withinms, the result rejects with the same reason. - If
promiseis still pending afterms, the result rejects with anErrorwhose message is"Timed out after <ms> ms"(for example"Timed out after 50 ms").
Once the result has settled, the timer must not keep running. The original promise is not cancelled; its late outcome is simply ignored.
Example 1
- Input
- withTimeout(delay(10, 'ok'), 50) withTimeout(delay(100, 'ok'), 50)
- Output
- resolves with 'ok' rejects with Error('Timed out after 50 ms')
Constraints
- 0 <= ms <= 10^4
- promise is a promise or a plain value.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 8. ⌘Enter runs, ⌘⇧Enter submits.