我是 FP-TS 的新手,但仍然不太了解如何使用TaskEither
. 我正在尝试异步读取文件,然后使用 yaml-parse-promise 解析生成的字符串。
==编辑==
我用文件的全部内容更新了代码以提供更多上下文,并应用了 MnZrK 提供的一些建议。抱歉,我还是 FP-TS 的新手,我仍在努力让类型匹配。
现在我的错误在于该map(printConfig)
行:
Argument of type '<E>(fa: TaskEither<E, AppConfig>) => TaskEither<E, AppConfig>' is not assignable to parameter of type '(a: TaskEither<unknown, AppConfig>) => Either<unknown, Task<any>>'.
Type 'TaskEither<unknown, AppConfig>' is not assignable to type 'Either<unknown, Task<any>>'.
Type 'TaskEither<unknown, AppConfig>' is missing the following properties from type 'Right<Task<any>>': _tag, rightts(2345)
[我通过使用来自 TaskEither 而不是来自 Either 库的 getOrElse 解决了这个问题]
==结束编辑==
我已经使用 IOEither 成功地执行了此操作,作为与该项目的同步操作:https ://github.com/anotherhale/fp-ts_sync-example 。
我还在这里查看了示例代码: https ://gcanti.github.io/fp-ts/recipes/async.html
完整代码在这里:https ://github.com/anotherhale/fp-ts_async-example
import { pipe } from 'fp-ts/lib/pipeable'
import { TaskEither, tryCatch, chain, map, getOrElse } from "fp-ts/lib/TaskEither";
import * as T from 'fp-ts/lib/Task';
import { promises as fsPromises } from 'fs';
const yamlPromise = require('js-yaml-promise');
// const path = require('path');
export interface AppConfig {
service: {
interface: string
port: number
};
}
function readFileAsyncAsTaskEither(path: string): TaskEither<unknown, string> {
return tryCatch(() => fsPromises.readFile(path, 'utf8'), e => e)
}
function readYamlAsTaskEither(content: string): TaskEither<unknown, AppConfig> {
return tryCatch(() => yamlPromise.safeLoad(content), e => e)
}
// function getConf(filePath:string){
// return pipe(
// readFileAsyncAsTaskEither(filePath)()).then(
// file=>pipe(file,foldE(
// e=>left(e),
// r=>right(readYamlAsTaskEither(r)().then(yaml=>
// pipe(yaml,foldE(
// e=>left(e),
// c=>right(c)
// ))
// ).catch(e=>left(e)))
// ))
// ).catch(e=>left(e))
// }
function getConf(filePath: string): TaskEither<unknown, AppConfig> {
return pipe(
readFileAsyncAsTaskEither(filePath),
chain(readYamlAsTaskEither)
)
}
function printConfig(config: AppConfig): AppConfig {
console.log("AppConfig is: ", config);
return config;
}
async function main(filePath: string): Promise<void> {
const program: T.Task<void> = pipe(
getConf(filePath),
map(printConfig),
getOrElse(e => {
return T.of(undefined);
})
);
await program();
}
main('./app-config.yaml')
结果输出是:
{ _tag: 'Right', right: Promise { <pending> } }
但我想要生成的 AppConfig:
{ service: { interface: '127.0.0.1', port: 9090 } }