Utils for async programming.
npm install @yume-chan/async!license
!GitHub Workflow Status
!Codecov

!npm type definitions
Utils for async programming.
- PromiseResolver
- AsyncOperationManager
`` ts
export type PromiseResolverState = 'running' | 'resolved' | 'rejected';
export class PromiseResolver
readonly promise: Promise
readonly state: PromiseResolverState;
resolve(value?: T | PromiseLike
reject(reason?: any): void;
}
`
C#, the origin of the async/await pattern, uses TaskCompletionSource to manage Tasks manually.
V8, the most commonly used JavaScript engine, uses PromiseResolver to manage Promises manually.
But in JavaScript, we only have the Promise constructor, and there is no way to know the Promise's state.
Now you can use this PromiseResolver class to create and manage Promises more conveniently.
` ts`
function delay(timeout: number): Promise
const resolver = new PromiseResolver
setTimeout(() => resolver.resolve(), timeout);
return resolver.promise;
}
` ts
export interface AsyncOperationInfo
id: number;
promise: Promise
}
export default class AsyncOperationManager {
add
resolve
reject(id: number, reason: Error): void;
}
`
Assume you have an RPC service, every operation has an ID, and the remote will return the result with this ID.
AsyncOperationManager can help you manage the IDs and convert callbacks to Promises.
` ts
declare const MyService;
const manager = new AsyncOperationManager();
MyService.on('complete', (id: number, result: number) => {
manager.resolve(id, result);
});
MyService.on('error', (id: number, message: string) => {
manager.reject(id, new Error(message));
});
function callService(payload: number): Promise
const { id, promise } = manager.add
MyService.post({ id, payload });
return promise;
}
``