简体   繁体   中英

setTimeout() and clearTimeout() with Promise in TypeScript (strict mode + all annotations)

I saw many examples of timer with Promise for JavaScript. Most of them are too complicated, but I suppose, it could be implemented more simply. However, I need the solution for TypeScript in "strict": true mode with all annotations.

I tried to do it until below code:

import Timeout = NodeJS.Timeout;

let testTimeout : Timeout;
const DELAY: number = 3000;

testTimeout = (): Promise<void> => (
  new Promise<void>( (resolve): void => {
    setTimeout(resolve, DELAY);
  })
);

testTimeout = testTimeout().then( () => {
  console.log('done');
});
clearTimeout(testTimeout);

It has errors:

TS2739: Type '() => Promise<void>' is missing the following properties from type 'Timeout': ref, refresh, unref

TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'Timeout' has no compatible call signatures.

I suppose, I do something wrong.

Try this:

function setTimeoutPromise(fn: () => number, delay: number): Promise<number> {
    return new Promise( (resolve, reject) => {
        setTimeout(() => {
            resolve(fn())
        }, delay)
    })
}

setTimeoutPromise(() => {
    console.log('resolving...');
    return 10;
}, 5000).then((res) => console.log('should print 10 after 5 secs', res));

this compiles fine with tsc --strict true . I am not sure if this what you are looking for though. Let me know!

There is another way of achieving this that I have just thought about:

import * as util from 'util';

const setTimeoutPromise = util.promisify((delay, fn) => setTimeout(fn, delay));
setTimeoutPromise(5000).then(() => console.log('hey you!'));

It might look a bit strange but it works. Basically .promisify expects a standard callback-last function to be passed to it as an argument where as the setTimeout has the opposite signature. So we reverse them:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM