aboutsummaryrefslogtreecommitdiff
path: root/files/ko/web/javascript/guide/using_promises/index.html
diff options
context:
space:
mode:
Diffstat (limited to 'files/ko/web/javascript/guide/using_promises/index.html')
-rw-r--r--files/ko/web/javascript/guide/using_promises/index.html52
1 files changed, 26 insertions, 26 deletions
diff --git a/files/ko/web/javascript/guide/using_promises/index.html b/files/ko/web/javascript/guide/using_promises/index.html
index abe9951baf..0f77bf8390 100644
--- a/files/ko/web/javascript/guide/using_promises/index.html
+++ b/files/ko/web/javascript/guide/using_promises/index.html
@@ -17,7 +17,7 @@ translation_of: Web/JavaScript/Guide/Using_promises
<p><code>createAudioFileAsync()</code>는 함수는 아래와 같이 사용됩니다.  </p>
-<pre class="notranslate"><code>function successCallback(result) {
+<pre><code>function successCallback(result) {
  console.log("Audio file ready at URL: " + result);
}</code>
@@ -31,11 +31,11 @@ translation_of: Web/JavaScript/Guide/Using_promises
<p>만약 <code>createAudioFileAsync()</code> 함수가 Promise를 반환해주도록 수정해본다면, 다음과 같이 간단하게 사용되어질 수 있습니다.</p>
-<pre class="notranslate"><code><span style='background-color: rgba(220, 220, 220, 0.5); font-family: consolas,"Liberation Mono",courier,monospace; font-style: inherit; font-weight: inherit;'>createAudioFileAsync(audioSettings).then(successCallback, failureCallback);</span></code></pre>
+<pre><code><span style='background-color: rgba(220, 220, 220, 0.5); font-family: consolas,"Liberation Mono",courier,monospace; font-style: inherit; font-weight: inherit;'>createAudioFileAsync(audioSettings).then(successCallback, failureCallback);</span></code></pre>
<p>…조금 더 간단하게 써보자면:</p>
-<pre class="notranslate"><code>const promise = createAudioFileAsync(audioSettings);
+<pre><code>const promise = createAudioFileAsync(audioSettings);
promise.then(successCallback, failureCallback);</code></pre>
<p>우리는 이와 같은 것을 <em>비동기 함수 호출</em>이라고 부릅니다. 이런 관례는 몇 가지 장점을 갖고 있습니다. 각각에 대해 한번 살펴보도록 합시다.</p>
@@ -58,13 +58,13 @@ promise.then(successCallback, failureCallback);</code></pre>
<p><code>then()</code> 함수는 새로운 promise를 반환합니다. 처음에 만들었던 promise와는 다른 새로운 promise입니다.</p>
-<pre class="brush: js notranslate">const promise = doSomething();
+<pre class="brush: js">const promise = doSomething();
const promise2 = promise.then(successCallback, failureCallback);
</pre>
<p>또는</p>
-<pre class="brush: js notranslate">const promise2 = doSomething().then(successCallback, failureCallback);
+<pre class="brush: js">const promise2 = doSomething().then(successCallback, failureCallback);
</pre>
<p>두 번째 promise는 <code>doSomething()</code> 뿐만 아니라 <code>successCallback</code> or <code>failureCallback</code> 의 완료를 의미합니다. <code>successCallback</code> or <code>failureCallback</code> 또한 promise를 반환하는 비동기 함수일 수도 있습니다. 이 경우 <code>promise2</code>에 추가 된 콜백은 <code>successCallback</code>또는 <code>failureCallback</code>에 의해 반환된 promise 뒤에 대기합니다.</p>
@@ -73,7 +73,7 @@ const promise2 = promise.then(successCallback, failureCallback);
<p>예전에는 여러 비동기 작업을 연속적으로 수행하면 고전적인 '지옥의 콜백 피라미드'가 만들어 졌었습니다.</p>
-<pre class="brush: js notranslate">doSomething(function(result) {
+<pre class="brush: js">doSomething(function(result) {
doSomethingElse(result, function(newResult) {
doThirdThing(newResult, function(finalResult) {
console.log('Got the final result: ' + finalResult);
@@ -84,7 +84,7 @@ const promise2 = promise.then(successCallback, failureCallback);
<p>모던한 방식으로 접근한다면, 우리는 콜백 함수들을 반환된 promise에 promise chain을 형성하도록 추가할 수 있습니다:</p>
-<pre class="brush: js notranslate">doSomething().then(function(result) {
+<pre class="brush: js">doSomething().then(function(result) {
return doSomethingElse(result);
})
.then(function(newResult) {
@@ -98,7 +98,7 @@ const promise2 = promise.then(successCallback, failureCallback);
<p><code>then</code> 에 넘겨지는 인자는 선택적(optional)입니다. 그리고 <code>catch(failureCallback)</code> 는 <code>then(null, failureCallback)</code> 의 축약입니다. 이 표현식을 <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">화살표 함수</a>로 나타내면 다음과 같습니다.</p>
-<pre class="brush: js notranslate">doSomething()
+<pre class="brush: js">doSomething()
.then(result =&gt; doSomethingElse(result))
.then(newResult =&gt; doThirdThing(newResult))
.then(finalResult =&gt; {
@@ -114,7 +114,7 @@ const promise2 = promise.then(successCallback, failureCallback);
<p>chain에서 작업이 실패한 후에도 새로운 작업을 수행하는 것이 가능하며 매우 유용합니다. (예 : <code>catch</code>) 다음 예를 읽으십시오:</p>
-<pre class="brush: js notranslate">new Promise((resolve, reject) =&gt; {
+<pre class="brush: js">new Promise((resolve, reject) =&gt; {
console.log('Initial');
resolve();
@@ -134,7 +134,7 @@ const promise2 = promise.then(successCallback, failureCallback);
<p>그러면 다음 텍스트가 출력됩니다.</p>
-<pre class="notranslate">Initial
+<pre>Initial
Do that
Do this, whatever happened before
</pre>
@@ -145,7 +145,7 @@ Do this, whatever happened before
<p>'콜백 지옥'에서 <code>failureCallback</code>이 3번 발생한 것을 기억 할 것입니다. promise chain에서는 단 한 번만 발생하는것과 비교되죠.</p>
-<pre class="notranslate"><code>doSomething()
+<pre><code>doSomething()
.then(result =&gt; doSomethingElse(result))
.then(newResult =&gt; doThirdThing(newResult))
.then(finalResult =&gt; console.log(`Got the final result: ${finalResult}`))
@@ -153,7 +153,7 @@ Do this, whatever happened before
<p>기본적으로 promise chain은 예외가 발생하면 멈추고 chain의 아래에서 catch를 찾습니다. 이것은 동기 코드가 어떻게 동작 하는지 모델링 한 것입니다.</p>
-<pre class="notranslate"><code>try {
+<pre><code>try {
const result = syncDoSomething();
const newResult = syncDoSomethingElse(result);
const finalResult = syncDoThirdThing(newResult);
@@ -164,7 +164,7 @@ Do this, whatever happened before
<p>비동기 코드를 사용한 이러한 대칭성은 ECMAScript 2017에서 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function"><code>async</code>/<code>await</code></a> 구문(Syntactic sugar) 에서 최고로 느낄 수 있습니다.</p>
-<pre class="notranslate"><code>async function foo() {
+<pre><code>async function foo() {
try {
const result = await doSomething();
const newResult = await doSomethingElse(result);
@@ -196,7 +196,7 @@ Do this, whatever happened before
<p>특히 유용한 사례 : {{Glossary("Node.js")}}로 코드를 작성할 때, 흔히 프로젝트에서 사용하는 모듈이 reject된 프로미스를 처리하지 않을 수 있습니다. 이런 경우 노드 실행시 콘솔에 로그가 남습니다. 이를 수집에서 분석하고 직접 처리할 수도 있습니다. 아니면 그냥 콘솔 출력을 어지럽히는 것을 막기 위해 그럴 수도 있죠. 이런 식으로 {{domxref("Window.unhandledrejection_event", "unhandledrejection")}}(<a href="/en-US/docs/Web/API/Window/unhandledrejection_event">영어</a>) 이벤트를 처리하는 핸들러를 추가하면 됩니다.</p>
-<pre class="notranslate"><code>window.addEventListener("unhandledrejection", event =&gt; {
+<pre><code>window.addEventListener("unhandledrejection", event =&gt; {
/* You might start here by adding code to examine the
promise specified by event.promise and the reason in
event.reason */
@@ -214,14 +214,14 @@ Do this, whatever happened before
<p>이상적인 프로그래밍 세계에서는 모든 비동기 함수는 promise을 반환해야 하지만. 불행히도 일부 API는 여전히 success 및 / 또는 failure 콜백을 전달하는 방식일거라 생각합니다.. 예를 들면 {{domxref ( "WindowTimers.setTimeout", "setTimeout ()")}} 함수가 있습니다.</p>
-<pre class="notranslate"><code>setTimeout(() =&gt; saySomething("10 seconds passed"), 10000);</code>
+<pre><code>setTimeout(() =&gt; saySomething("10 seconds passed"), 10000);</code>
</pre>
<p>예전 스타일의 콜백과 Promise를 합치는것 문제가 있습니다. 함수 <code>saySomething()</code>이 실패하거나 프로그래밍 오류가 있으면 아무 것도 잡아 내지 않습니다. <code>setTimeout</code>의 문제점 입니다.</p>
<p>다행히도 우리는 <code>setTimeout</code>을 Promise로 감쌀 수 있습니다. 가장 좋은 방법은 가능한 가장 낮은 수준에서 문제가되는 함수를 래핑 한 다음 다시는 직접 호출하지 않는 것입니다.</p>
-<pre class="notranslate"><code>const wait = ms =&gt; new Promise(resolve =&gt; setTimeout(resolve, ms));
+<pre><code>const wait = ms =&gt; new Promise(resolve =&gt; setTimeout(resolve, ms));
wait(10000).then(() =&gt; saySomething("10 seconds")).catch(failureCallback);</code>
</pre>
@@ -236,14 +236,14 @@ wait(10000).then(() =&gt; saySomething("10 seconds")).catch(failureCallback);</c
<p>우리는 병렬로 작업을 시작하고 모든 작업이 다음과 같이 끝날 때까지 기다릴 수 있습니다.</p>
-<pre class="notranslate"><code>Promise.all([func1(), func2(), func3()])
+<pre><code>Promise.all([func1(), func2(), func3()])
.then(([result1, result2, result3]) =&gt; { /* use result1, result2 and result3 */ });</code></pre>
<p>Sequential composition is possible using some clever JavaScript:</p>
<p>고급진 JavaScript를 사용하여 순차적 구성이 가능합니다.</p>
-<pre class="notranslate"><code>[func1, func2, func3].reduce((p, f) =&gt; p.then(f), Promise.resolve())
+<pre><code>[func1, func2, func3].reduce((p, f) =&gt; p.then(f), Promise.resolve())
.then(result3 =&gt; { /* use result3 */ });</code>
</pre>
@@ -251,19 +251,19 @@ wait(10000).then(() =&gt; saySomething("10 seconds")).catch(failureCallback);</c
<p>이것은 재사용 가능한 작성 기능으로 만들 수 있는데, 이는 함수형 프로그래밍에서 일반적인 방식입니다.</p>
-<pre class="notranslate"><code>const applyAsync = (acc,val) =&gt; acc.then(val);
+<pre><code>const applyAsync = (acc,val) =&gt; acc.then(val);
const composeAsync = (...funcs) =&gt; x =&gt; funcs.reduce(applyAsync, Promise.resolve(x));</code>
</pre>
<p><code>composeAsync()</code> 함수는 여러 함수를 인수로 받아들이고 composition 파이프 라인을 통해 전달되는 초기 값을 허용하는 새 함수를 반환합니다.</p>
-<pre class="notranslate"><code>const transformData = composeAsync(func1, func2, func3);
+<pre><code>const transformData = composeAsync(func1, func2, func3);
const result3 = transformData(data);</code>
</pre>
<p>ECMAScript 2017에서는 async / await를 사용하여 순차적 구성을보다 간단하게 수행 할 수 있습니다.</p>
-<pre class="notranslate"><code>let result;
+<pre><code>let result;
for (const f of [func1, func2, func3]) {
result = await f(result);
}
@@ -275,13 +275,13 @@ for (const f of [func1, func2, func3]) {
<p>놀라움(역자 주. 에러가 난다거나, 코드가 문제가 생긴다거나..했을때의 그 놀라움..)을 피하기 위해 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then">then()</a></code>에 전달 된 함수는 already-resolved promise에 있는 경우에도 동기적으로 호출되지 않습니다.</p>
-<pre class="notranslate"><code>Promise.resolve().then(() =&gt; console.log(2));
+<pre><code>Promise.resolve().then(() =&gt; console.log(2));
console.log(1); // 1, 2</code>
</pre>
<p>즉시 실행되는 대신 전달 된 함수는 마이크로 태스크 대기열에 저장됩니다. 즉, 자바 스크립트 이벤트 루프의 현재 실행이 끝날 때 대기열이 비면 나중에 실행됩니다.</p>
-<pre class="notranslate"><code>const wait = ms =&gt; new Promise(resolve =&gt; setTimeout(resolve, ms));
+<pre><code>const wait = ms =&gt; new Promise(resolve =&gt; setTimeout(resolve, ms));
wait().then(() =&gt; console.log(4));
Promise.resolve().then(() =&gt; console.log(2)).then(() =&gt; console.log(3));
@@ -299,7 +299,7 @@ console.log(1); // 1, 2, 3, 4</code></pre>
<p>중첩은 <code>catch</code> 문 범위를 제한하는 제어 구조입니다. 특히, 중첩 된 <code>catch</code>는 중첩 된 범위 외부의 체인에있는 오류가 아닌 범위 및 그 이하의 오류 만 잡습니다. 올바르게 사용하면 오류 복구에서보다 정확한 결과를 얻을 수 있습니다.</p>
-<pre class="notranslate"><code>doSomethingCritical()
+<pre><code>doSomethingCritical()
.then(result =&gt; doSomethingOptional(result)
.then(optionalResult =&gt; doSomethingExtraNice(optionalResult))
.catch(e =&gt; {})) // Ignore if optional stuff fails; proceed.
@@ -315,7 +315,7 @@ console.log(1); // 1, 2, 3, 4</code></pre>
<p>promise chains을 작성할 때 주의해야 할 몇 가지 일반적인 실수는 다음과 같습니다. 이러한 실수 중 몇 가지는 다음 예제에서 나타납니다.</p>
-<pre class="notranslate"><code>// Bad example! Spot 3 mistakes!
+<pre><code>// Bad example! Spot 3 mistakes!
doSomething().then(function(result) {
doSomethingElse(result) // Forgot to return promise from inner chain + unnecessary nesting
@@ -332,7 +332,7 @@ doSomething().then(function(result) {
<p>좋은 경험 법칙은 항상 약속의 사슬을 반환하거나 종결하는 것이며, 새로운 약속을 얻 자마자 즉각적으로 돌려서 물건을 평평하게하는 것입니다.</p>
-<pre class="notranslate"><code>doSomething()
+<pre><code>doSomething()
.then(function(result) {
return doSomethingElse(result);
})