aboutsummaryrefslogtreecommitdiff
path: root/files/ko/web/javascript/reference/statements/async_function/index.html
diff options
context:
space:
mode:
Diffstat (limited to 'files/ko/web/javascript/reference/statements/async_function/index.html')
-rw-r--r--files/ko/web/javascript/reference/statements/async_function/index.html243
1 files changed, 243 insertions, 0 deletions
diff --git a/files/ko/web/javascript/reference/statements/async_function/index.html b/files/ko/web/javascript/reference/statements/async_function/index.html
new file mode 100644
index 0000000000..5a986c8af4
--- /dev/null
+++ b/files/ko/web/javascript/reference/statements/async_function/index.html
@@ -0,0 +1,243 @@
+---
+title: async function
+slug: Web/JavaScript/Reference/Statements/async_function
+tags:
+ - Example
+ - JavaScript
+ - Promise
+ - async
+ - await
+translation_of: Web/JavaScript/Reference/Statements/async_function
+---
+<div>{{jsSidebar("Statements")}}</div>
+
+<p><code><strong>async function</strong></code> 선언은 {{jsxref("Global_Objects/AsyncFunction","AsyncFunction")}}객체를 반환하는 하나의 비동기 함수를 정의합니다. 비동기 함수는 이벤트 루프를 통해 비동기적으로 작동하는 함수로, 암시적으로 {{jsxref("Promise")}}를 사용하여 결과를 반환합니다. 그러나 비동기 함수를 사용하는 코드의 구문과 구조는, 표준 동기 함수를 사용하는것과 많이 비슷합니다.</p>
+
+<div class="noinclude">
+<p>또한 {{jsxref("Operators/async_function", "async function expression", "", 1)}}을 사용해서 async function을 선언할 수 있습니다.</p>
+</div>
+
+<div>{{EmbedInteractiveExample("pages/js/statement-async.html", "taller")}}</div>
+
+<div class="hidden">
+<p>이 데모에 대한 소스가 여기에 있다. 기여하고싶다면 다음의 주소에서 Clone하고 pull request하라 : <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a></p>
+</div>
+
+<h2 id="Syntax">Syntax</h2>
+
+<pre class="syntaxbox notranslate" dir="rtl">async function <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) {
+ <em>statements</em>
+}
+</pre>
+
+<h3 id="매개변수">매개변수</h3>
+
+<dl>
+ <dt><code>name</code></dt>
+ <dd>함수의 이름.</dd>
+</dl>
+
+<dl>
+ <dt><code>param</code></dt>
+ <dd>함수에게 전달되기 위한 인자의 이름.</dd>
+</dl>
+
+<dl>
+ <dt><code>statements</code></dt>
+ <dd><font face="Consolas, Liberation Mono, Courier, monospace">함수본문을 구성하는 내용.</font></dd>
+ <dt>
+ <h3 id="반환_값"><font face="Consolas, Liberation Mono, Courier, monospace">반환 값</font></h3>
+
+ <p>Promise : async 함수에 의해 반환 된 값으로 해결되거나 async함수 내에서 발생하는 캐치되지 않는 예외로 거부되는 값.</p>
+ </dt>
+</dl>
+
+<h2 id="Description">Description</h2>
+
+<p><code>async</code> 함수에는 {{jsxref ( "Operators / await", "await")}}식이 포함될 수 있습니다. 이 식은 <code>async</code> 함수의 실행을 일시 중지하고 전달 된 <code>Promise</code>의 해결을 기다린 다음 <code>async</code> 함수의 실행을 다시 시작하고 완료후 값을 반환합니다.</p>
+
+<div class="blockIndicator note">
+<p><code>await</code> 키워드는 <code>async</code> 함수에서만 유효하다는 것을 기억하십시오. <code>async</code> 함수의 본문 외부에서 사용하면 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a>가 발생합니다.</p>
+</div>
+
+<div class="note">
+<p>async/await함수의 목적은 사용하는 여러 promise의 동작을 동기스럽게 사용할 수 있게 하고, 어떠한 동작을 여러 promise의 그룹에서 간단하게 동작하게 하는 것이다.<br>
+ promise가 구조화된 callback과 유사한 것 처럼 async/await또한 제네레이터(generator)와 프로미스(promise)를 묶는것과 유사하다.</p>
+</div>
+
+<p><code>async</code> 함수는 항상 promise를 반환합니다. 만약 <code>async</code> 함수의 반환값이 명시적으로 promise가 아니라면 암묵적으로 promise로 감싸집니다.</p>
+
+<p>예를 들어</p>
+
+<pre class="notranslate">async function foo() {
+ return 1
+}</pre>
+
+<p>위 코드는 아래와 같습니다.</p>
+
+<pre class="notranslate">function foo() {
+ return Promise.resolve(1)
+}</pre>
+
+<p><code>async</code> 함수의 본문은 0개 이상의 <code>await</code> 문으로 분할된 것으로 생각할 수 있습니다. 첫번째 <code>await</code> 문을 포함하는 최상위 코드는 동기적으로 실행됩니다. 따라서 <code>await</code> 문이 없는 <code>async</code> 함수는 동기적으로 실행됩니다. 하지만 <code>await</code> 문이 있다면 <code>async</code> 함수는 항상 비동기적으로 완료됩니다.</p>
+
+<p>예를 들어</p>
+
+<pre class="notranslate">async function foo() {
+ await 1
+}</pre>
+
+<p>위 코드는 아래와 같습니다.</p>
+
+<pre class="notranslate">function foo() {
+ return Promise.resolve(1).then(() =&gt; undefined)
+}
+</pre>
+
+<h2 id="Examples">Examples</h2>
+
+<h3 id="Simple_example">Simple example</h3>
+
+<pre class="notranslate"><code>var resolveAfter2Seconds = function() {
+ console.log("starting slow promise");
+ return new Promise(resolve =&gt; {
+ setTimeout(function() {
+ resolve(20);
+ console.log("slow promise is done");
+ }, 2000);
+ });
+};
+
+var resolveAfter1Second = function() {
+ console.log("starting fast promise");
+ return new Promise(resolve =&gt; {
+ setTimeout(function() {
+ resolve(10);
+ console.log("fast promise is done");
+ }, 1000);
+ });
+};
+
+var sequentialStart = async function() {
+ console.log('==SEQUENTIAL START==');
+
+ // If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise.
+ const slow = await resolveAfter2Seconds();
+  console.log(slow);
+
+ const fast = await resolveAfter1Second();
+ console.log(fast);
+}
+
+var concurrentStart = async function() {
+ console.log('==CONCURRENT START with await==');
+ const slow = resolveAfter2Seconds(); // starts timer immediately
+ const fast = resolveAfter1Second();
+
+ console.log(await slow);
+ console.log(await fast); // waits for slow to finish, even though fast is already done!
+}
+
+var stillConcurrent = function() {
+ console.log('==CONCURRENT START with Promise.all==');
+ Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then((messages) =&gt; {
+ console.log(messages[0]); // slow
+ console.log(messages[1]); // fast
+ });
+}
+
+var parallel = function() {
+ console.log('==PARALLEL with Promise.then==');
+ resolveAfter2Seconds().then((message)=&gt;console.log(message));
+ resolveAfter1Second().then((message)=&gt;console.log(message));
+}
+
+sequentialStart(); // after 2 seconds, logs "slow", then after 1 more second, "fast"
+// wait above to finish
+setTimeout(concurrentStart, 4000); // after 2 seconds, logs "slow" and then "fast"
+// wait again
+setTimeout(stillConcurrent, 7000); // same as concurrentStart
+// wait again
+setTimeout(parallel, 10000); // trully parallel: after 1 second, logs "fast", then after 1 more second, "slow"</code></pre>
+
+<div class="warning">
+<h4 id="await_와_Promisethen을_혼동하지_마세요"><code>await</code> 와 <code>Promise#then</code>을 혼동하지 마세요</h4>
+
+<p><code>sequentialStart</code> 에서, 첫 번째 <code>await</code>는 2초의 대기 시간을 갖고,  다시 두 번째 <code>await</code>에서 1초의 대기 시간을 갖습니다. 두 번째 타이머는 첫 번째 타이머가 완료될 때 까지 생성되지 않습니다.</p>
+
+<p><code>concurrentStart</code> 에서, 두 타이머 모두 생성 된 다음 <code>await</code> 합니다. 타이머가 동시에 실행되고 있지만, <code>await</code> 호출은 여전히 연속적 실행중이므로, 두 번째 <code>await</code> 는 첫 번째 호출이 끝날 때 까지 대기합니다. 이렇게하면 3초가 아니라, 가장 느린 타이머에 필요한 2초가 필요합니다. <code>stillConcurrent</code> 에서도 <code>Promise.all</code> 을 사용하여 같은 일이 발생합니다.</p>
+
+<p>두 개 이상의 프러미스를 동시에 wait 하고 싶다면, <code>Promise#then</code>을 사용하여 예제와 같이 <code>parallel</code> 를 수행할 수 있습니다.</p>
+</div>
+
+<h3 id="async함수를_사용한_promise_chain_재작성"><code>async</code>함수를 사용한 promise chain 재작성</h3>
+
+<p>{{jsxref("Promise")}} 를 반환하는 API는 promise chain을 만들며 여러 파트의 함수로 나뉜다.<br>
+ 아래 코드를 보자.</p>
+
+<pre class="brush: js notranslate">function getProcessedData(url) {
+ return downloadData(url) // returns a promise
+ .catch(e =&gt; {
+ return downloadFallbackData(url) // returns a promise
+ })
+ .then(v =&gt; {
+ return processDataInWorker(v); // returns a promise
+ });
+}
+</pre>
+
+<p>위의 코드는 하나의 async함수로 아래와 같이 쓰여질 수도 있다.</p>
+
+<pre class="brush: js notranslate">async function getProcessedData(url) {
+ let v;
+ try {
+ v = await downloadData(url);
+ } catch (e) {
+ v = await downloadFallbackData(url);
+ }
+ return processDataInWorker(v);
+}
+</pre>
+
+<p>위 예제에서는 return 구문에 await 구문이 없다는 것에 주목하자. 이는 async function의 반환값이 암묵적으로 {{jsxref("Promise.resolve")}}로 감싸지기 때문이다.</p>
+
+<h2 id="Specifications">Specifications</h2>
+
+<table>
+ <thead>
+ <tr>
+ <th scope="col">Specification</th>
+ <th scope="col">Status</th>
+ <th scope="col">Comment</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>{{SpecName('ESDraft', '#sec-async-function-definitions', 'async function')}}</td>
+ <td>{{Spec2('ESDraft')}}</td>
+ <td>Initial definition in ES2017.</td>
+ </tr>
+ <tr>
+ <td>{{SpecName('ES8', '#sec-async-function-definitions', 'async function')}}</td>
+ <td>{{Spec2('ES8')}}</td>
+ <td></td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Browser_compatibility">Browser compatibility</h2>
+
+<div class="hidden">
+<p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>and send us a pull request.</p>
+</div>
+
+<p>{{Compat("javascript.statements.async_function")}}</p>
+
+<h2 id="함께_보기">함께 보기</h2>
+
+<ul>
+ <li>{{jsxref("Operators/async_function", "async function expression")}}</li>
+ <li>{{jsxref("AsyncFunction")}} object</li>
+ <li>{{jsxref("Operators/await", "await")}}</li>
+ <li><a href="http://innolitics.com/10x/javascript-decorators-for-promise-returning-functions/">"Decorating Async Javascript Functions" on "innolitics.com"</a></li>
+</ul>