# astatus 中文文档

规范地址：https://npmcn.com/package/astatus/

版本：0\.1\.6
npm 元数据更新时间：2026-11-03T01:53:54.119Z
中文译文更新时间：2026-11-03T04:04:59.606Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：33.8 kB，11 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- peer 依赖：vue \>=3\.3\.0
- 首次发布：2026-03-16T07:43:34.967Z
- 最新版本发布：2026-11-03T01:53:53.943Z
- 已发布版本数：7（近 12 个月 7 个）

## 中文简介

异步状态信号。没有数据，没有获取——只有舞台。

## 安装

```sh
npm install astatus
```

也可以使用：`pnpm add astatus`、`yarn add astatus`、`bun add astatus`

## README

# astatus

异步状态信号。没有数据，没有获取——只有舞台。

```js
import astatus from "astatus";

const AS = astatus();

AS.pending();
await fetchUser();
await processData(); // however many steps
AS.success(); // you decide when
```

大多数异步状态库将状态绑定到数据或获取逻辑。 `astatus` 不喜欢。  
这是一个独立的信号，你可以把它注入任何流中，在你选择的任何点。

* * *

## 安装

```bash
npm install astatus
```

* * *

## 使用

```js
import astatus, { STATUS } from "astatus";

const loginAS = astatus({ name: "login" });

// Inject status at the right moment
loginAS.pending();
const data = await fetchUser();
await syncStore(data); // sync or async, as many steps as needed
loginAS.success();

// Read
console.log(loginAS.status); // 'success'
console.log(loginAS.isSuccess); // true
```

* * *

## API

> 所有的例子都使用 `const AS = astatus()` 除非另有说明。

### 创建

```js
astatus({ name?, status? })
```

| 选项 | 类型 | 默认的 | 描述 |
| --- | --- | --- | --- |
| `name` | `string` | `null` | 调试日志名称 |
| `status` | `string` | `'initial'` | 初始状态 |

* * *

### 状态阶段

`astatus` 管理四个内置阶段。这些是库的核心——其他一切都建立在它们之上。

| 阶段 | 描述 |
| --- | --- |
| `initial` | 尚未启动-默认值 |
| `pending` | 在进步 |
| `success` | 成功完成 |
| `failure` | 失败，带有可选的错误值 |

您可以通过调用相应的方法在这四个阶段之间移动。这就是整个想法。

```js
AS.pending();
await doSomething();
AS.success();
```

对于生命周期之外的任何东西， `AS.custom('uploading')` 接受任何字符串。

* * *

### 注入

```js
AS.initial()
AS.pending()
AS.success()
AS.failure(error?)      // optional error value
AS.custom('uploading')  // any string outside built-in stages
```

* * *

### 读

```js
AS.status; // 'initial' | 'pending' | 'success' | 'failure' | custom
AS.error; // value passed to failure(), otherwise null
AS.isInitial;
AS.isPending;
AS.isSuccess;
AS.isFailure;
AS.isCustom; // true if current status is not a built-in stage
AS.isLocked;
```

* * *

### 观察

```js
// All changes
const unsub = AS.subscribe((curr, prev) => {
  console.log(curr.status, prev.status)
})

// Specific status — triggers on both entry and exit
const unwatch = AS.watch('success', (curr, prev) => { ... })
AS.watch(['success', 'failure'], (curr, prev) => { ... })

// Entry only — triggers once on transition into the status
const unwatch = AS.when('success', (curr, prev) => { ... })

// Cleanup
unsub()
unwatch()
```

* * *

### 等待

```js
// As a timing gate — wait for the right moment, then continue
await AS.wait();
await AS.wait("success");

// As a result — inspect what happened
const { status, error, timeout, immediate } = await AS.wait();
const result = await AS.wait(["success", "failure"], 15); // timeout in seconds
```

| 场 | 描述 |
| --- | --- |
| `status` | 解析时的状态（快照） |
| `error` | 解析时错误 |
| `timeout` | `true` 如果超时 |
| `immediate` | `true` 如果已经处于目标状态 |
| `destroyed` | `true` 如果实例在解析之前被销毁 |

如果 `destroy()` 被称为while a `wait()` 是悬而未决的，它立即解决 `destroyed: true`.

* * *

### 锁

```js
AS.lock(); // block all status changes
AS.unlock(); // unblock
```

* * *

### 重置/销毁

```js
AS.reset(); // back to initial, clears error and lock
AS.destroy(); // resolves all pending wait()s, clears all listeners, blocks all further changes
```

* * *

### 状态不变

```js
import { STATUS } from "astatus";

STATUS.INITIAL; // 'initial'
STATUS.PENDING; // 'pending'
STATUS.SUCCESS; // 'success'
STATUS.FAILURE; // 'failure'
```

* * *

## Vue / next

`astatus` 包括一个Vue可组合的开箱即用。不需要额外的安装。

```ts
import { useAstatus } from "astatus/vue";
```

### 基本用法

```vue
<script setup>
import { useAstatus } from "astatus/vue";

const loginAS = useAstatus({ name: "login" });

const handleLogin = async () => {
    loginAS.pending();
    try {
        await fetchUser();
        loginAS.success();
    } catch (e) {
        loginAS.failure(e);
    }
};
</script>

<template>
    <button :disabled="loginAS.isPending" @click="handleLogin">
        {{ loginAS.isPending ? "Loading..." : "Login" }}
    </button>
    <p v-if="loginAS.isFailure">{{ loginAS.error }}</p>
</template>
```

### 反应性

`status` 和 `error` 是只读引用。 `isInitial`， `isPending`， `isSuccess`， `isFailure`， `isCustom` 都是计算值——都是响应式的，可以安全地在模板中使用。

ref在模板中会自动展开，所以 `.value` 这里不需要。

```ts
const AS = useAstatus();

// script: use .value
watch(AS.isPending, (val) => {
    console.log("pending:", val);
});

// template: no .value needed
// <p v-if="AS.isPending">...</p>
```

> **注意：** 破坏破坏了反应性。总是直接使用返回的对象。
> 
> ```ts
> // ✅
> const loginAS = useAstatus();
> // loginAS.isPending in template
> 
> // ❌ reactivity lost
> const { isPending } = useAstatus();
> ```

### 自动清理

可组合的自动调用 `destroy()` 通过卸载组件 `onUnmounted`． 在大多数情况下不需要手动清理。

如果你使用 `useAstatus` 在组件外部（例如在一个Pinia store中），自动清理不适用- call `destroy()` 手动完成时。

```ts
// Pinia store
const AS = useAstatus();

// when no longer needed
AS.destroy();
```

要使实例在其组件之后保持存活（例如，在路由更改时缓存），pass `autoDestroy: false`． 你拥有它的生命周期-呼叫 `destroy()` 如果它应该结束的话，你自己。在组件内部创建时需要Vue 3.5+，因为早期版本在卸载时停止组件的计算。

```ts
const cache = {};
const boardAS = (cache.board ??= useAstatus({ name: "board", autoDestroy: false }));
```

### next中的wait（）

`wait()` 使用 `setTimeout` 在内部。在next中，避免在SSR期间调用它-在内部使用它 `onMounted` 或者用 `import.meta.client`.

```ts
// ✅ safe
onMounted(async () => {
    await AS.wait();
});

// ✅ safe
if (import.meta.client) {
    await AS.wait();
}
```

### 要求

-   Vue >= 3.3.0

* * *

## 笔记

-   `subscribe` / `watch` / `when` 返回一个退订函数——调用它来清理。
-   `destroy()` 解决所有悬而未决的问题 `wait()` 立即调用，然后清除所有侦听器。
-   侦听器错误被捕获并单独记录，而不会破坏其他侦听器。

* * *

## 许可证

麻省理工学院

* * *

_自述部分编辑与人工智能的帮助。_

## 常见问题

### astatus 是什么？

异步状态信号。没有数据，没有获取——只有舞台。

### 如何安装 astatus？

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

### astatus 支持 TypeScript 吗？

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

### astatus 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### astatus 可以商用吗？

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

### astatus 还在维护吗？

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

