我看到了许多Promise for JavaScript中的计时器示例。它们大多数都太复杂了,但是我想,它可以更简单地实现。但是,我需要带有所有注释的"strict": true
模式下的TypeScript解决方案。
我一直尝试这样做,直到出现以下代码:
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);
它有错误:
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.
我想我做错了。
答案 0 :(得分:1)
尝试一下:
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));
使用tsc --strict true
可以正常编译。我不确定这是否是您要寻找的东西。让我知道!
还有我刚刚想到的另一种实现方法:
import * as util from 'util';
const setTimeoutPromise = util.promisify((delay, fn) => setTimeout(fn, delay));
setTimeoutPromise(5000).then(() => console.log('hey you!'));
它可能看起来有些奇怪,但是可以工作。基本上.promisify
期望将标准的callback-last函数作为参数传递给它,因为setTimeout
具有相反的签名。所以我们将它们反转:)