> 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-ko/sdk7/programming-patterns/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-ko/sdk7/architecture/systems.md#system-execution-order).

코드를 동기적으로 실행하면 일관성을 유지할 수 있습니다. 코드의 명령이 어떤 순서로 실행되는지 항상 알 수 있기 때문입니다.

반면 씬에서는 다음 프레임을 구성하기 위해 초당 여러 번 업데이트가 필요합니다. 코드의 일부가 응답하는 데 너무 오래 걸리면 메인 스레드 전체가 멈춰 프레임 속도가 느려집니다.

따라서 경우에 따라 일부 명령은 비동기적으로 실행하는 것이 좋습니다. 이렇게 하면 작업을 시작한 뒤, 그동안 씬은 다음 코드 줄을 계속 실행할 수 있습니다. 씬은 여전히 단일 스레드에서 모든 작업을 실행하지만, 비동기 작업이 응답을 기다리는 동안 나머지 코드가 차단되지는 않습니다.

응답하는 데 시간이 걸릴 수 있는 외부 서비스에 의존하는 작업에 특히 유용합니다. 응답을 기다리는 유휴 시간이 다른 작업을 차단하지 않도록 할 수 있기 때문입니다.

예를 들면 다음과 같습니다.

* REST API에서 데이터를 가져올 때
* 블록체인에서 트랜잭션을 수행할 때

{% hint style="warning" %}
**📔 참고**: 작업이 완료되기 전에 씬의 여러 프레임이 렌더링될 수 있다는 점에 유의하세요. 비동기 작업이 완료되는 동안의 상황에도 유연하게 대응할 수 있도록 씬 코드를 작성해야 합니다.
{% endhint %}

## 비동기 함수 실행

함수에 `async` 를 지정하면, 대기하는 동안 씬의 나머지 코드를 차단하지 않고 비동기적으로 실행됩니다.

```ts
// 비동기 함수 선언
async function myAsyncTask() {
	// 함수의 단계 실행
}

// 비동기 함수 호출
myAsyncTask()

// 나머지 코드가 계속 실행됨
```

## executeTask 함수

executeTask() `executeTask()` 함수는 람다 함수를 비동기적으로 실행합니다. `executeTask()` 이 함수는 하나의 문에서 함수를 선언하고 실행할 수 있게 해줍니다.

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

// 나머지 코드가 계속 실행됨
```

## then 함수

then `then` 함수는 람다 함수를 인수로 받으며, 앞선 문이 완료된 후에만 실행합니다. 이 람다 함수에는 앞선 문이 반환하는 값을 전달하는 입력을 선택적으로 지정할 수 있습니다.

```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-ko/sdk7/interactivity/button-events/register-callback.md) 방식을 사용하면 이를 처리하는 시스템을 명시적으로 만들 필요가 없지만, 같은 작업이 백그라운드에서 수행됩니다.
{% endhint %}

참조 [클릭 이벤트](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/button-events/click-events.md) 및 [레이캐스팅](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/raycasting.md).

{% hint style="info" %}
**💡 팁**: 레이캐스트 결과를 처리하는 데 계산량이 많다면(예: 경로 탐색 알고리즘 실행) 해당 계산을 비동기 함수에서 실행하는 것이 좋습니다.
{% endhint %}

## await 문

await `await`  문은 다음 코드 줄로 넘어가기 전에 응답을 기다리도록 실행을 일시 중지합니다. `await`  문은 비동기 코드 블록 안에서만 사용할 수 있습니다.

```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()

// 나머지 코드는 계속 실행됩니다
```

위 예제는 외부 API에서 데이터를 가져오는 `fetch()`  작업을 포함하는 함수를 실행합니다. 이 `fetch()`  작업은 비동기 작업입니다. 서버가 응답하는 데 얼마나 걸릴지 예측할 수 없기 때문입니다. 하지만 다음 줄에서 결과를 JSON으로 파싱하려면 이 작업의 출력이 준비되어 있어야 합니다. 여기서 `await`  문은 작업이 값을 반환한 뒤에만 다음 줄이 실행되도록 합니다. 마찬가지로 `response.json()`  함수도 비동기 함수지만, 다음 줄에서 JSON을 로그로 출력하려면 먼저 파싱이 완료되어야 합니다. 두 번째 `await`  문은 JSON 파싱이 끝난 뒤에만 다음 줄이 실행되도록 합니다. 파싱에 시간이 얼마나 걸리든 상관없습니다.

## 함수 호출에 시간 제한 설정

setTimeout `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 `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-ko/sdk7/programming-patterns/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.
