【问题标题】:How do I annotate this function for Flow如何为 Flow 注释此函数
【发布时间】:2016-09-26 04:38:28
【问题描述】:

我在使用 Flow (https://github.com/facebook/flow) 的文件中有这个 JS 函数

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

我将如何对此进行注释?

【问题讨论】:

  • 这真的不是你使用异步函数的方式。按照这个逻辑,promiseWrapper 将是异步函数,而您只需执行 static async promiseWrapper(fn, ...args){ await fn(...args); }

标签: javascript node.js ecmascript-6 flowtype


【解决方案1】:

正如在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;

});

【讨论】:

  • 我在上面提到过,但在这里也想提一下,new Promise 的这种用法是一种反模式。 promiseWrapper 应该是异步函数,它应该只返回结果,而不是调用 resolve 回调。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-14
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多