首页 > 解决方案 > 从高地流中的 aync 函数返回时如何处理元组?

问题描述

我使用tsc@2.3.4highland@^2.13.0

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

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

所以我所做的基本上是:创建承诺,并行化它们的消费,最后我想要一个[string, string[]]via流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[]]>'.

标签: typescriptes6-promisehighland.js

解决方案


的类型声明parallel是错误的。更正后,您的代码将通过类型检查器而没有flatten. 我已经提交了一个拉取请求来修复打字;您可以从那里将更正的类型的副本添加到您的项目中。


推荐阅读