[p-cancelable] introduce typings (#18478)

This commit is contained in:
Dimitri Benin
2017-07-28 12:45:51 -07:00
committed by Andy
parent 0f8472649f
commit 9fb941e644
4 changed files with 117 additions and 0 deletions
+30
View File
@@ -0,0 +1,30 @@
// Type definitions for p-cancelable 0.3
// Project: https://github.com/sindresorhus/p-cancelable#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = PCancelable;
declare const PCancelable: PCancelableConstructor;
interface PCancelableConstructor extends PromiseConstructor {
readonly prototype: PCancelable.PCancelable<any>;
readonly CancelError: PCancelable.CancelErrorConstructor;
fn<T, R>(wrapper: (onCancel: (fn?: () => void) => void, input: T) => PromiseLike<R>): (input: T) => PCancelable.PCancelable<R>;
new<T>(executor: (onCancel: (fn?: () => void) => void, resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): PCancelable.PCancelable<T>;
}
declare namespace PCancelable {
interface PCancelable<T> extends Promise<T> {
readonly canceled: boolean;
cancel(): void;
}
interface CancelErrorConstructor extends ErrorConstructor {
new (): CancelError;
}
interface CancelError extends Error {
readonly name: 'CancelError';
}
}
+64
View File
@@ -0,0 +1,64 @@
/// <reference types="node" />
import PCancelableCtor = require('p-cancelable');
import { EventEmitter } from "events";
const cancelablePromise: PCancelableCtor.PCancelable<{}> = new PCancelableCtor((onCancel, resolve, reject) => {
class Worker extends EventEmitter {
close() {
}
}
const worker = new Worker();
onCancel(() => {
worker.close();
});
worker.on('finish', resolve);
worker.on('error', reject);
});
cancelablePromise
.then(value => {
console.log('Operation finished successfully:', value);
})
.catch(reason => {
if (cancelablePromise.canceled) {
// Handle the cancelation here
console.log('Operation was canceled');
return;
}
throw reason;
});
setTimeout(() => {
cancelablePromise.cancel();
}, 10000);
const fn = PCancelableCtor.fn((onCancel: (fn?: () => void) => void, input: string) => {
const job = {
start() {
return Promise.resolve(10);
},
cleanup() {
}
};
onCancel(() => {
job.cleanup();
});
return job.start();
});
const promise = fn('input');
let num: number;
promise.then(innum => num = innum);
if (!promise.canceled) {
promise.cancel();
}
const err: PCancelableCtor.CancelError = new PCancelableCtor.CancelError();
throw err;
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"p-cancelable-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }