![](/img/trans.png)
[英]How to handle promise rejection when creating a highland stream from a promise?
[英]How to deal with tuples when returned from an aync function within highland streams?
我使用tsc@2.3.4
和highland@^2.13.0
。
我有一个异步函数,返回一个[string, string[]]
类型的元组。
过去,我曾在高地工作过,我知道我可以通过创建带有承诺的新高地流并通过展平承诺来解决承诺。
因此,我要做的基本上是:创建promise,并行化它们的使用,最后我希望通过flatten
一个[string, string[]]
流。
然而高地的实际行为与我的预期相矛盾。
在这里,我的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
。 我已经提交了一个拉动请求,以修复打字问题; 您可以从那里将更正的类型的副本添加到您的项目中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.