2016-05-27 9 views
1

Ich habe diese Funktion in einer Datei JS wo ich Fluss (https://github.com/facebook/flow)Wie mit Anmerkungen versehen ich diese Funktion für den Durchfluss

// @flow 
static promiseWrapper(fn, ...args) { 
    return new Promise(
    async function(resolve, reject) { 
     try { 
     await fn(...args); 
     resolve(); 
     } catch (e) { 
     reject(e); 
     } 
    } 
) 
} 

Wie würde ich über annotieren diese gehen?

+1

Das ist wirklich nicht der Fall ist, wie Sie Asynchron-Funktionen verwenden. Mit dieser Logik wäre 'promiseWrapper' die Async-Funktion, und Sie würden einfach 'statische Async-Versprechen machen. Wrapper (fn, ... args) {erwarten fn (... args); } ' – loganfsmyth

Antwort

2

Wie auf der github project issue diskutiert, würde dies meine vorgeschlagene Lösung sein:

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; 

}); 
+1

Ich oben erwähnt, aber wollte auch hier erwähnen, diese Verwendung von' New Promise' ist ein Antipattern. 'promiseWrapper' sollte die Async-Funktion sein und dies sollte nur das Ergebnis zurückgeben, nicht einen' resolve' Callback aufrufen. – loganfsmyth

Verwandte Themen