Created
September 9, 2016 02:46
-
-
Save lukiano/3ec1d9e9674593b3475c38d7feadc87b to your computer and use it in GitHub Desktop.
await task
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Task} from 'aff'; | |
import {PromiseLikeTask} from './util/async-task'; | |
describe('Task', function () { | |
it.only('test1', () => { | |
return johndoe().exec(); | |
}); | |
}); | |
async function johndoe(): PromiseLikeTask<void> { | |
console.log('First number is 1'); | |
const result = await johndoe2(4); | |
console.log(`Second number is ${result}`); | |
await johndoe3(25); | |
console.log('3'); | |
throw new Error('xx'); | |
} | |
function johndoe2(i: number) { | |
return Task.try(() => { | |
console.log(`Working... ${i}`); | |
return i; | |
}); | |
} | |
async function johndoe3(i: number): PromiseLikeTask<void> { | |
console.log(`First number is ${i}`); | |
const result = await johndoe2(i + 1); | |
console.log(`Second number is ${result}`); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Task, Context} from 'aff'; | |
const at_cls = require('continuation-local-storage').createNamespace('cls-aff-task'); | |
export class PromiseLikeTask<T> extends Task<T> implements PromiseLike<T> { | |
constructor(callback: (resolve: (t: T | PromiseLike<T> | Task<T>) => void, reject: (error: any) => void) => void) { | |
super(ctx => new Promise<T>((pResolve, pReject) => { | |
at_cls.set('context', ctx); | |
const myResolve = (t: T | PromiseLike<T> | Task<T>) => pResolve(t instanceof Task ? t.run(ctx) : t); | |
callback(myResolve, pReject); | |
})); | |
} | |
public then<U>(onfulfilled?: (value: T) => (PromiseLike<U> | U), | |
onrejected?: (reason: any) => (PromiseLike<U> | U)): PromiseLike<U> { | |
return this.when({ | |
ok: (value: T) => { | |
onfulfilled(value); | |
return Task.of(value); | |
}, | |
err: (err: Error) => { | |
onrejected(err); | |
return Task.fail(err); | |
} | |
}).run(at_cls.get('context')); | |
} | |
public run(ctx: Context): Promise<T> { | |
const superrun = super.run.bind(this); | |
return new Promise<T>(pResolve => at_cls.run(() => pResolve(superrun(ctx)))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment