> For the complete documentation index, see [llms.txt](https://docs.decentraland.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/bian-cheng-mo-shi/async-functions.md). Agents can also search and read this documentation through its [MCP server](https://docs.decentraland.org/~gitbook/mcp).

# 异步函数

了解何时以及如何在场景代码中运行异步函数。

## 概览

场景中的大部分代码都在单个线程中同步运行。这意味着命令会逐行按顺序执行。每条命令都必须先等待上一条命令执行完毕，才能开始执行。

场景系统中的函数也会逐个执行，并遵循 [优先级顺序](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jia-gou/systems.md#system-execution-order).

同步运行代码可以确保一致性，因为你始终可以确定代码中的命令会按什么顺序运行。

另一方面，场景需要每秒更新多次，以生成下一帧。如果代码中的某一部分响应时间过长，整个主线程就会被卡住，导致帧率下降。

因此，在某些情况下，你会希望某些命令异步运行。这意味着你可以启动一项任务，同时让场景继续执行后续代码。场景仍然在单个线程中运行，但异步任务等待响应时，其余代码不会被阻塞。

对于依赖外部服务的任务，这一点尤其有用，因为外部服务可能需要一段时间才能响应；你肯定不希望等待响应的空闲时间阻塞其他任务。

例如：

* 从 REST API 获取数据时
* 在区块链上执行交易时

{% hint style="warning" %}
**📔 注意**：请记住，在任务执行完毕之前，场景可能已经渲染了好几帧。请确保场景代码足够灵活，能够处理异步任务完成期间的各种中间状态。
{% endhint %}

## 运行异步函数

将任意函数标记为 `async` ，使其异步运行，并在等待期间不阻塞场景的其他代码。

```ts
// 声明异步函数
async function myAsyncTask() {
	// 执行函数中的步骤
}

// 调用异步函数
myAsyncTask()

// 其余代码继续执行
```

## executeTask 函数

这个 `executeTask()` 函数会异步执行一个 lambda 函数。 `executeTask()` 让我们能够在同一条语句中声明并执行该函数。

```ts
executeTask(async () => {
	let data = await myAsyncTask()
	console.log(data)
})

// 其余代码继续执行
```

## then 函数

该 `then` 函数接受一个 lambda 函数作为参数，该函数只有在前一条语句执行完毕后才会执行。这个 lambda 函数可以选择接收输入，这些输入会映射到前一条语句的返回值。

```ts
myAsyncTask().then((data) => {
	console.log(data)
})
```

{% hint style="warning" %}
**📔 注意**：通常最好使用 `executeTask` 这种方式，而不是使用 `then` 函数。如果过于依赖 `then` 在多个嵌套层级中使用函数，最终可能会陷入所谓的“回调地狱”，此时代码会变得很难阅读和维护。
{% endhint %}

## PointerEvents 和 RayCast 函数

当场景使用 `PointerEvent` 或 `RayCast` 组件时，引擎会异步执行碰撞计算。随后，引擎会向场景返回一个结果事件；该事件可能会在调用事件后的一个或多个游戏循环刻后才到达。

因此，你需要创建一个系统，在结果到达的帧中处理这些结果。

{% hint style="warning" %}
**📔 注意**：如果你通过以下方式处理点击 [**注册回调**](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/register-callback.md) 方法，无需显式创建系统来处理此问题，后台也会执行相同的操作。
{% endhint %}

请参阅 [点击事件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/click-events.md) 和 [射线检测](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/raycasting.md).

{% hint style="info" %}
**💡 提示**：如果处理射线检测结果需要大量计算（例如运行寻路算法），可以考虑在异步函数中执行这些计算。
{% endhint %}

## await 语句

一个 `await` 语句会强制程序等待响应后，才继续执行下一行代码。 `await` 语句只能在 async 代码块中使用。

```ts
// 声明函数
async function myAsyncTask() {
	try {
		let response = await fetch(callUrl)
		let json = await response.json()
		console.log(json)
	} catch {
		console.log('failed to reach the URL')
	}
}

// 调用函数
myAsyncTask()

// 代码的其余部分继续执行
```

上面的示例会执行一个包含 `fetch()` 操作的函数，以从外部 API 获取数据。 `fetch()` 操作是异步的，因为我们无法预测服务器需要多长时间才能响应。不过，在将结果解析为 JSON 之前，必须先准备好该操作的输出。 `await` 语句可确保下一行只会在该操作返回值后才运行。同样， `response.json()` 函数也是异步的，但必须先解析 JSON，下一行才能将其记录下来。第二个 `await` 语句会强制下一行等到 JSON 解析完成后才调用，无论这需要多长时间。

## 为函数调用设置超时

使用 `setTimeout` 可在运行某些代码行之前等待一段时间。它接受两个参数：

* 要执行的函数
* 执行该函数前等待的毫秒数

以下示例会等待 1000 毫秒（即 1 秒），然后执行一个简单函数，该函数会向控制台输出一条消息。

```ts
import { timers } from '@dcl/sdk/ecs'

console.log('This gets printed right away')

timers.setTimeout(() => {
	// 延迟后运行的函数
    console.log('This gets printed after 1 second')
}, 1000)
```

此 `clearTimeout` 可用于取消 `setTimeout` 仍在等待执行的函数。 `setTimeout` 返回一个计时器 ID（一个数字），随后你可以将其传递给 `clearTimeout`。在这种情况下，变量 `timeoutId` 是在调用 `setTimeout`时获取的，随后传递给 `clearTimeout` 以取消计时器。

```ts
import { timers } from '@dcl/sdk/ecs'

const timeoutId = timers.setTimeout(() => {
    console.log('Wait 1 second until executing this function')
}, 1000)

timers.clearTimeout(timeoutId)
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/bian-cheng-mo-shi/async-functions.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
