# @abraham/remotedata 中文文档

规范地址：https://npmcn.com/package/%40abraham/remotedata/

版本：2\.0\.0
npm 元数据更新时间：2026-11-02T06:35:02.030Z
中文译文更新时间：2026-11-06T17:41:57.699Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40abraham/remotedata
原文对照：https://npmcn.com/package/%40abraham/remotedata/?lang=original
项目主页：https://github.com/abraham/remotedata#readme
源码仓库：https://github.com/abraham/remotedata

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：25.3 kB，8 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=22
- 运行依赖：0 个
- 首次发布：2018-07-13T23:03:58.164Z
- 最新版本发布：2026-11-02T06:35:01.673Z
- 近 30 天下载量：2558（2026-10-05 至 2026-11-03，npm 官方下载统计）
- 已发布版本数：20（近 12 个月 1 个）

## 中文简介

轻量级类型Script远程数据执行

## 安装

```sh
npm install @abraham/remotedata
```

也可以使用：`pnpm add @abraham/remotedata`、`yarn add @abraham/remotedata`、`bun add @abraham/remotedata`

## README

[![Version Status](https://img.shields.io/npm/v/@abraham/remotedata.svg?style=flat&label=version&colorB=4bc524)](https://npmjs.com/package/@abraham/remotedata) [![Build Status](https://github.com/abraham/remotedata/workflows/Index/badge.svg)](https://github.com/abraham/remotedata/actions) [![npm bundle size (minified + gzip)](https://img.shields.io/bundlephobia/minzip/@abraham/remotedata.svg?style=flat&colorB=4bc524)](https://bundlephobia.com/result?p=@abraham/remotedata)

# 远程数据

轻量级类型Script远程数据执行

## 安装

```sh
npm install @abraham/remotedata
```

## 使用量

读取 [以 Web 组件( 和 TypeScript) 来 slaying a UI Antipatten](https://bendyworks.com/blog/slaying-a-ui-antipattern-with-web-components-and-typescript) 更详尽的指南.

此类是获得一个帖子的示例类( type ) `Post`从远程HTTP API.

```ts
import {
  Failure,
  fold,
  Initialized,
  Pending,
  Success,
  type RemoteData,
} from '@abraham/remotedata';

interface Post {
  title: string;
}

// Define what the RemoteData Failure and Success types will be.
type State = RemoteData<number, Post>;

class Thing {
  // Set the initial state as Initialized.
  private state: State = new Initialized();

  // Use `fold` to easily define logic based on the current state.
  // Fold takes four methods as parameters in the order of Initialized, Pending, Failure, and
  // Success and returns a method that takes a `RemoteData` state instance as a parameter. When
  // the returned method gets called with a `RemoteData` state, the method matching the correct
  // state gets called.
  private view = fold<string, number, Post>(
    // What to do if the state is Initialized.
    () => 'Initialized',
    // What to do if the request is Pending.
    () => 'Loading...',
    // What to do if the request fails.
    (error) => `Error: ${error}`,
    // What to do if the request succeeds.
    (post) => `Got post ${post.title}`,
  );

  constructor() {
    // On instantiation start the remote call and render the current state.
    void this.getPost();
    this.render();
  }

  private async getPost(): Promise<void> {
    // Before starting the remote call set the current state to Pending.
    this.state = new Pending();
    // Perform the actual remote request.
    const response = await fetch('https://api.example.com/post');
    if (response.ok) {
      // If the request succeeds set the state to Success with the returned data.
      const post = (await response.json()) as Post;
      this.state = new Success(post);
    } else {
      // If the request does not succeed set the state to Failure with the reason.
      this.state = new Failure(response.status);
    }
    // Render the new state.
    this.render();
  }

  private render(): void {
    // Render the current state in your UI.
    // `this.view` is executed with the current state as a parameter.
    const text = this.view(this.state);
    // Maybe put it in a template.
  }
}
```

包括使用 [类型警卫](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)。 。 。 .

```ts
import { isSuccess, type RemoteData } from '@abraham/remotedata';
import { getState, type Post } from './state';

// Define what the RemoteData Failure and Success types will be.
type State = RemoteData<number, Post>;

const state: State = getState();
if (isSuccess(state)) {
  // state is known to be of type Success<Post>
  console.log(state.data.title);
}
```

## 帮助者

```ts
import {
  andThen,
  combine,
  fromPromise,
  map,
  mapError,
  withDefault,
} from '@abraham/remotedata';

// Success or Failure from a promise.
const post = await fromPromise(fetchPost());
// Transform Success data or the Failure error; other states pass through.
const title = map(post, (p) => p.title);
const message = mapError(post, (error) => String(error));
// Chain into another RemoteData when Success.
const author = andThen(post, (p) => getAuthor(p.authorId));
// Success data or a fallback.
const text = withDefault(title, 'Untitled');
// First Failure, else Pending, else Initialized, else Success with all values.
const both = combine([post, author]);
```

# 参考资料

-   [精灵如何杀死一个UI反派](http://blog.jenkster.com/2016/06/how-elm-slays-a-ui-antipattern.html)
-   [以角击杀UI反相机](https://medium.com/@joanllenas/slaying-a-ui-antipattern-with-angular-4c7536fafc54)
-   [以"流"来杀死UI反派](https://medium.com/@gcanti/slaying-a-ui-antipattern-with-flow-5eed0cfb627b)
-   [在反应中杀死一个UI反扩散器](https://medium.com/javascript-inside/slaying-a-ui-antipattern-in-react-64a3b98242c)
-   [在"幻想之地"上放枪](https://medium.com/javascript-inside/slaying-a-ui-antipattern-in-fantasyland-907cbc322d2a)
-   [远程数据状态为 Enum](http://holko.pl/2016/06/09/data-state-as-an-enum/)

## 常见问题

### @abraham/remotedata 是什么？

轻量级类型Script远程数据执行

### 如何安装 @abraham/remotedata？

在项目目录运行 npm install @abraham/remotedata，或使用 pnpm add / yarn add / bun add。

### @abraham/remotedata 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @abraham/remotedata 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @abraham/remotedata 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=22。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @abraham/remotedata 可以商用吗？

@abraham/remotedata 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @abraham/remotedata 的下载量有多少？

根据 npm 官方下载统计，@abraham/remotedata 在 2026/10/05 – 2026/11/03 这 30 天内被下载 2,558 次，日均约 85 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @abraham/remotedata 还在维护吗？

最新版本 2\.0\.0 发布于 2026/11/02（5 天前）；至今共发布 20 个版本，其中过去 12 个月发布了 1 个；首次发布于 2018/07/14。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

