---
title: "onceAsync"
description: "Wrap an async function so it runs once, concurrent callers share one promise, and a rejection clears the cache for retry."
canonical_url: "https://core.mhaibaraai.cn/en/docs/utilities/async/once-async"
---
# onceAsync

> Wrap an async function so it runs once, concurrent callers share one promise, and a rejection clears the cache for retry.

## Usage

`onceAsync` returns a new function: the first call runs the original function, concurrent calls reuse the same promise, and a successful result is cached. A rejection clears the cache so the next call runs again.

```ts
import { onceAsync } from '@movk/core'

// Load an optional dependency only once
const loadPmtiles = onceAsync(() => import('pmtiles'))

const [a, b] = await Promise.all([loadPmtiles(), loadPmtiles()])
a === b // true

// One-time registration
const register = onceAsync(async () => {
  const { Protocol } = await loadPmtiles()
  addProtocol('pmtiles', new Protocol().tile)
})
```

## API

### `onceAsync(fn)`

Wrap an async function so it runs once and shares its result.

### Parameters

**fn** (`() => Promise<T>`) *required*: Async function to wrap; errors thrown synchronously are returned as a rejection too.

### Returns

**Returns** (`() => Promise<T>`): A function that returns the shared promise.

## Changelog

See commit history for [src/utilities/async/onceAsync.ts](https://github.com/mhaibaraai/movk-core/commits/main/src/utilities/async/onceAsync.ts).

---

- [GitHub](https://github.com/mhaibaraai/movk-core/blob/main/src/utilities/async/onceAsync.ts)


## Sitemap

See the full [sitemap](https://core.mhaibaraai.cn/sitemap.md) for all pages.
