我将这个JS函数放在一个文件中,我使用Flow(https://github.com/facebook/flow)
// @flow
static promiseWrapper(fn, ...args) {
return new Promise(
async function(resolve, reject) {
try {
await fn(...args);
resolve();
} catch (e) {
reject(e);
}
}
)
}
我该如何解释这个?
答案 0 :(得分:2)
如github project issue所述,这将是我提出的解决方案:
class Foo {
// We are using generics <U, T> to define the input type / output type (may be the same... I don't know the use-cases)
static promiseWrapper<U, T>(fn: (...args: Array<U>) => Promise<T>, ...args: Array<U>): Promise<T> {
return new Promise(async (resolve, reject) => {
try {
// I felt like handling the return value of this await function
const ret = await fn(...args);
resolve(ret);
} catch (e) {
reject(e);
}
});
}
}
// Most of the type inference comes from this function
function fun(...args: Array<number>): Promise<string> {
const ret = args.reduce((result, num) => (result + num), 0);
return Promise.resolve(ret.toString());
}
const myProm = Foo.promiseWrapper(fun, 1, 2, 3);
// Here, total should be inferred as string, since our `fun` function returns a Promise<string>
// Generic function definition <T> picks this up correctly :-)
myProm.then((total) => {
// $ExpectError : total should be inferred as string, hence it should fail on numerical addition
const foo: number = total + 1;
});