javascript - 返回“响应”对象或元组的模式的名称
问题描述
在编写 JavaScript/TypeScript 时,我有时会实现一种模式,其中函数返回响应对象(如下所示)或响应“元组”(仅表示包含两个项目的数组),而不是原始值。像这样的东西:
example.js
function getName() {
if (userPressedOk) {
return {status: "OK", name: getName()}
else {
return {status: "FAIL", name: ""}
}
}
example.ts
function getName(): { status: string; jobName: string } {
if (userPressedOk) {
return {status: "OK", name: getName()}
else {
return {status: "FAIL", name: ""}
}
}
这是一个稍微做作的例子,但这是基本思想。我试图模仿我在函数式编程语言中看到的风格。这种模式有名字吗?
解决方案
我见过它们称为Result Objects。
在您说要借用的功能语言中,通常调用相应的类型Result
或Either
(尽管它通常在失败情况下提供错误消息,而不是默认值)。
推荐阅读
- bash - 如何将带有空格的目录作为参数传递给函数?
- tensorflow - 使用 fit_generator 的基本 RNN 训练不会输出预期的形状
- flutter - Flutter 无法将 CameraPreview 小部件设置为匹配屏幕尺寸
- sql-server - 如何跳过错误并继续运行 SQL 查询?
- python-3.x - 读取 pem 证书期间 python 3.6 出现 x509 错误
- extjs - 如何在 Extjs 的组合框中传递树存储
- c++ - 本书示例在类声明中使用“显式”关键字。无效吗?
- python - 将 Opencv 安装到 Anaconda 的问题
- c++ - 时间执行悖论
- swift - 如何将 GMT 日期转换为系统日期格式?