typescript - 从高地流中的 aync 函数返回时如何处理元组?
问题描述
我使用tsc@2.3.4
和highland@^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[]]>'.
解决方案
的类型声明parallel
是错误的。更正后,您的代码将通过类型检查器而没有flatten
. 我已经提交了一个拉取请求来修复打字;您可以从那里将更正的类型的副本添加到您的项目中。
推荐阅读
- javascript - 从您的网站在 google 上搜索的搜索栏
- python - 如何使用 numpy 向量化在两个巨大数据帧的同一列中查找不同的数据列?
- php - PHP VSCode Xdebug Error::listen EADDRINUSE: address already in use :::9111
- javascript - 在隐藏要搜索的列表时创建一个工作搜索栏
- performance - Google Drive API 非常慢
- javascript - 访问 gtm.formsubmit 上的 Google 跟踪代码管理器 dataLayer 字段值
- amazon-web-services - AWS Cloudformation 为 ec2 用户数据调用 bash 脚本
- huawei-mobile-services - 将文件存储在华为 Drive Kit 中
- javascript - 从函数调用时数组未按预期返回
- sqlite - 为什么 ORDER BY DESC 不能正常工作?