【问题标题】:How to deal with tuples when returned from an aync function within highland streams?从高地流中的异步函数返回时如何处理元组?
【发布时间】:2018-09-18 16:27:03
【问题描述】:

我使用tsc@2.3.4highland@^2.13.0

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

我过去曾与 highland 合作过,我知道我可以通过使用 Promise 创建一个新的 highland 流并通过将其展平来解决 Promise 来使用 Promise。

所以我所做的基本上是:创建 Promise,并行化它们的消费,最后我想要一个 [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”。

所以我完全丢失了元组并得到一个包含所有元素的流的大“混乱”。

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


我发现当我不展平流时,我得到了我的结果,但 typescript 会抛出一个错误:

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[]]>'.

【问题讨论】:

    标签: typescript es6-promise highland.js


    【解决方案1】:

    parallel 的类型声明错误。更正后,您的代码将通过类型检查器,而没有 flatten。我已经提交a pull request 来修复打字问题;您可以从那里将更正的类型的副本添加到您的项目中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-04
      • 1970-01-01
      • 2020-07-29
      • 2023-03-08
      • 1970-01-01
      • 2017-06-13
      • 2020-09-30
      相关资源
      最近更新 更多