vitalets / await-timeout

A Promise-based API for setTimeout / clearTimeout

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question about clear timeout

gou4shi1 opened this issue · comments

Hello, I have a small quesiton about this code:

import Timeout from 'await-timeout';

const timer = new Timeout();
try {
  await Promise.race([
    fetch('https://example.com'),
    timer.set(1000, 'Timeout!')
  ]);
} finally {
  timer.clear();
}

Without a timer cleanup you may get unexpected effects in you code - as all promises in Promise.race are get fulfille

Why the timer need to be cleanup? race() only accept the first settled promise.

Imagine you have the following code:

const timer = new Timeout();
try {
  await Promise.race([
    fetch('https://example.com'),
    timer.set(1000).then(() => {
       console.log('Operation timeout');
       throw new Error('Timeout'); 
    });
  ]);
} finally {
  timer.clear();
}

Even if fetch resolve first, we will get Operation timeout in console.

PS: in modern Node.js env there is built-in timers API with the same functionality.