Let's look at the example async
function from promisejs.org , which is allows us to wait for promises using generators:
function async(makeGenerator){
return function () {
var generator = makeGenerator.apply(this, arguments);
function handle(result){
// result => { done: [Boolean], value: [Object] }
if (result.done) return Promise.resolve(result.value);
return Promise.resolve(result.value).then(function (res){
return handle(generator.next(res));
}, function (err){
return handle(generator.throw(err));
});
}
try {
return handle(generator.next());
} catch (ex) {
return Promise.reject(ex);
}
}
}
Example usage:
var login = async(function* (username, password, session) {
var user = yield getUser(username);
var hash = yield crypto.hashAsync(password + user.salt);
if (user.hash !== hash) {
throw new Error('Incorrect password');
}
session.setUser(user);
});
My question: How should both of these functions be annotated in TypeScript, in orded to keep type safety?
What I've tried: I know the async
function returns a Promise<T>
, but I'm not sure what T
should be. I guess it should depend on the generator passed in, but what type does a generator have? There is GeneratorFunction
in the typings for nodejs or bluebird (can't remember which), but that one is not generic so I can't do async(makeGenerator: GeneratorFunction<T>): Promise<T>
as I'd want to.
but I'm not sure what T should be
In your case login
returns nothing to Promise<void>
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.