javascript - 如何为 Flow 注释此函数

标签 javascript node.js ecmascript-6 flowtype

我在使用 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);
      }
    }
  )
}

我将如何对此进行注释?

最佳答案

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

});

关于javascript - 如何为 Flow 注释此函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37490255/

相关文章:

javascript - 在 2 个符号的索引处查找并拆分字符串

mysql - JSON.stringify 字符串是否可以防止 (My)SQL 注入(inject)?

javascript - 如何获取函数内部创建的变量?

node.js - 显示当前使用 node/express/socket.io 构建的聊天中的用户

javascript - 条件数组解构

javascript - fetch请求返回的中间结果应该叫什么?一个 Blob 还是只是响应?

javascript - ReactJS/ES6 : Searching Japanese text using includes?

Javascript倒计时器来更改图像和链接

javascript - 将 forEach 函数转换为 reduce 函数

javascript - jwplayer 在 80% 的视频上调用事件