Skip to content
This repository has been archived by the owner on Mar 7, 2024. It is now read-only.

Commit

Permalink
🐞 fix: return method for api with task type
Browse files Browse the repository at this point in the history
  • Loading branch information
starriv committed May 10, 2022
1 parent f180dd9 commit 1751fd6
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 7 deletions.
15 changes: 15 additions & 0 deletions packages/remax-framework-shared/src/__tests__/promisify.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,21 @@ describe('promisify', () => {
expect(success).toBeCalledTimes(1);
});

it('resolve by complete param', async () => {
function api({ complete }: any) {
complete('complete');
}

const promisifyAPI = promisify(api);
const complete = jest.fn();

await promisifyAPI({
complete,
});

expect(complete).toBeCalledTimes(1);
});

it('promisify api and reject when failed', () => {
function api({ fail }: any) {
fail('error');
Expand Down
40 changes: 33 additions & 7 deletions packages/remax-framework-shared/src/promisify.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
export interface PromisifyArgs<SuccessArg, FailArg> {
export interface PromisifyArgs<SuccessArg, FailArg, CompleteArg> {
success?: (args: SuccessArg) => void;
fail?: (args: FailArg) => void;
complete?: (args: CompleteArg) => void;
}

export function promisify<Arg = any, SuccessArg = any, FailArg = any>(
api: (arg: Arg & PromisifyArgs<SuccessArg, FailArg>) => void
export function promisify<Arg = any, SuccessArg = any, FailArg = any, CompleteArg = any>(
api: (arg: Arg & PromisifyArgs<SuccessArg, FailArg, CompleteArg>) => any
) {
return (arg: Arg & PromisifyArgs<SuccessArg, FailArg> = {} as Arg) => {
return new Promise<SuccessArg>((resolve, reject) => {
return (arg: Arg & PromisifyArgs<SuccessArg, FailArg, CompleteArg> = {} as Arg) => {
let task: any = null;
const p = new Promise<{ [key: string]: any }>((resolve, reject) => {
const promisifyArg: any = arg;

api({
task = api({
...promisifyArg,
success: (res: SuccessArg) => {
if (promisifyArg && typeof promisifyArg.success === 'function') {
Expand All @@ -24,7 +25,32 @@ export function promisify<Arg = any, SuccessArg = any, FailArg = any>(
}
reject(res);
},
complete: (res: CompleteArg) => {
if (promisifyArg && typeof promisifyArg.complete === 'function') {
promisifyArg.complete(res);
}
resolve(res);
},
});
});

const taskMethods = [
'abort',
'onHeadersReceived',
'offHeadersReceived',
'onProgressUpdate',
'offProgressUpdate',
'onChunkReceived',
'offChunkReceived',
];
task &&
taskMethods.forEach(method => {
if (method in task) {
// @ts-ignore
p[method] = task[method].bind(task);
}
});

return p;
};
}

0 comments on commit 1751fd6

Please sign in to comment.