从高原流中的aync函数返回时,如何处理元组?

时间:2018-09-18 16:27:04

标签: typescript es6-promise highland.js

我使用tsc@2.3.4highland@^2.13.0

我有一个异步函数,该函数返回类型为[string, string[]]的元组。

我过去曾在高地工作过,我知道我可以通过创建带有承诺的新高地流并通过展平承诺来解决承诺。

所以我要做的基本上是:创建承诺,使它们的使用并行化,最后我要通过[string, string[]]来一个flatten的流。

但高原的实际行为与我的预期相矛盾。

这是展示我期望的TypeScript代码:

import * as highland from "highland";

const somethingAsync = async (s: string): Promise<[string, string[]]> => {
    return [s, s.split("")];
};

const data = [
    "foo",
    "bar",
    "baz",
    "poit",
    "gnarf",
];

const stream: Highland.Stream<[string, string[]]> = highland(data)
    .map((input: string) => highland(somethingAsync(input))) // wrapping the promises into a highland stream
    .parallel(3) // processing it in parallel
    .flatten(); // flattening it to resolve the promises

stream.each((shouldBeATuple: [string, string[]]) => {
    console.log(shouldBeATuple);

    const [item1, item2] = shouldBeATuple;
    console.log(item1, item2);
});

我希望shouldBeATuple实际上是一个元组。但是相反,我得到了所有元素的流,好像flatten过于扁平化了。

我希望它是第一次迭代:

 ["foo", ["f","o","o"]];

第二个:

 ["bar", ["b","a","r"]];

我得到的却是:

 "foo",

,然后跟着:“ f”,“ o”,“ o”,“ bar”,“ b”,“ a”,“ r”。

因此,我完全丢失了元组,并获得其中包含所有元素的流的一个大“混乱”。

使用异步函数时如何获取元组流?


我发现当我不展平流时,我得到了结果,而打字稿将抛出错误:

15 const stream: Highland.Stream<[string, string[]]> = highland(data)
         ~~~~~~
src/tuple.ts(15,7): error TS2322: Type 'Stream<Stream<[string, string[]]>>' is not assignable to type 'Stream<[string, string[]]>'.
  Type 'Stream<[string, string[]]>' is not assignable to type '[string, string[]]'.
    Property '0' is missing in type 'Stream<[string, string[]]>'.

1 个答案:

答案 0 :(得分:1)

parallel的类型声明是错误的。更正后,您的代码将通过类型检查器,而不会使用flatten。我已提交a pull request来修正输入;您可以从那里将更正的类型的副本添加到您的项目中。