From 06bc06d023186d8d36f90c88e76a9e4c03446534 Mon Sep 17 00:00:00 2001 From: alattalatta Date: Thu, 16 Dec 2021 02:01:24 +0900 Subject: Remove notranslate from JS guides --- .../web/javascript/guide/using_promises/index.html | 52 +++++++++++----------- 1 file changed, 26 insertions(+), 26 deletions(-) (limited to 'files/ko/web/javascript/guide/using_promises/index.html') 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

createAudioFileAsync()는 함수는 아래와 같이 사용됩니다.  

-
function successCallback(result) {
+
function successCallback(result) {
   console.log("Audio file ready at URL: " + result);
 }
 
@@ -31,11 +31,11 @@ translation_of: Web/JavaScript/Guide/Using_promises
 
 

만약 createAudioFileAsync() 함수가 Promise를 반환해주도록 수정해본다면, 다음과 같이 간단하게 사용되어질 수 있습니다.

-
createAudioFileAsync(audioSettings).then(successCallback, failureCallback);
+
createAudioFileAsync(audioSettings).then(successCallback, failureCallback);

…조금 더 간단하게 써보자면:

-
const promise = createAudioFileAsync(audioSettings);
+
const promise = createAudioFileAsync(audioSettings);
 promise.then(successCallback, failureCallback);

우리는 이와 같은 것을 비동기 함수 호출이라고 부릅니다. 이런 관례는 몇 가지 장점을 갖고 있습니다. 각각에 대해 한번 살펴보도록 합시다.

@@ -58,13 +58,13 @@ promise.then(successCallback, failureCallback);

then() 함수는 새로운 promise를 반환합니다. 처음에 만들었던 promise와는 다른 새로운 promise입니다.

-
const promise = doSomething();
+
const promise = doSomething();
 const promise2 = promise.then(successCallback, failureCallback);
 

또는

-
const promise2 = doSomething().then(successCallback, failureCallback);
+
const promise2 = doSomething().then(successCallback, failureCallback);
 

두 번째 promise는 doSomething() 뿐만 아니라 successCallback or failureCallback 의 완료를 의미합니다. successCallback or failureCallback 또한 promise를 반환하는 비동기 함수일 수도 있습니다. 이 경우 promise2에 추가 된 콜백은 successCallback또는 failureCallback에 의해 반환된 promise 뒤에 대기합니다.

@@ -73,7 +73,7 @@ const promise2 = promise.then(successCallback, failureCallback);

예전에는 여러 비동기 작업을 연속적으로 수행하면 고전적인 '지옥의 콜백 피라미드'가 만들어 졌었습니다.

-
doSomething(function(result) {
+
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);
 
 

모던한 방식으로 접근한다면, 우리는 콜백 함수들을 반환된 promise에 promise chain을 형성하도록 추가할 수 있습니다:

-
doSomething().then(function(result) {
+
doSomething().then(function(result) {
   return doSomethingElse(result);
 })
 .then(function(newResult) {
@@ -98,7 +98,7 @@ const promise2 = promise.then(successCallback, failureCallback);
 
 

then 에 넘겨지는 인자는 선택적(optional)입니다. 그리고 catch(failureCallback) 는 then(null, failureCallback) 의 축약입니다. 이 표현식을 화살표 함수로 나타내면 다음과 같습니다.

-
doSomething()
+
doSomething()
 .then(result => doSomethingElse(result))
 .then(newResult => doThirdThing(newResult))
 .then(finalResult => {
@@ -114,7 +114,7 @@ const promise2 = promise.then(successCallback, failureCallback);
 
 

chain에서 작업이 실패한 후에도 새로운 작업을 수행하는 것이 가능하며 매우 유용합니다. (예 : catch) 다음 예를 읽으십시오:

-
new Promise((resolve, reject) => {
+
new Promise((resolve, reject) => {
     console.log('Initial');
 
     resolve();
@@ -134,7 +134,7 @@ const promise2 = promise.then(successCallback, failureCallback);
 
 

그러면 다음 텍스트가 출력됩니다.

-
Initial
+
Initial
 Do that
 Do this, whatever happened before
 
@@ -145,7 +145,7 @@ Do this, whatever happened before

'콜백 지옥'에서 failureCallback이 3번 발생한 것을 기억 할 것입니다. promise chain에서는 단 한 번만 발생하는것과 비교되죠.

-
doSomething()
+
doSomething()
 .then(result => doSomethingElse(result))
 .then(newResult => doThirdThing(newResult))
 .then(finalResult => console.log(`Got the final result: ${finalResult}`))
@@ -153,7 +153,7 @@ Do this, whatever happened before
 
 

기본적으로 promise chain은 예외가 발생하면 멈추고 chain의 아래에서 catch를 찾습니다. 이것은 동기 코드가 어떻게 동작 하는지 모델링 한 것입니다.

-
try {
+
try {
   const result = syncDoSomething();
   const newResult = syncDoSomethingElse(result);
   const finalResult = syncDoThirdThing(newResult);
@@ -164,7 +164,7 @@ Do this, whatever happened before
 
 

비동기 코드를 사용한 이러한 대칭성은 ECMAScript 2017에서 async/await 구문(Syntactic sugar) 에서 최고로 느낄 수 있습니다.

-
async function foo() {
+
async function foo() {
   try {
     const result = await doSomething();
     const newResult = await doSomethingElse(result);
@@ -196,7 +196,7 @@ Do this, whatever happened before
 
 

특히 유용한 사례 : {{Glossary("Node.js")}}로 코드를 작성할 때, 흔히 프로젝트에서 사용하는 모듈이 reject된 프로미스를 처리하지 않을 수 있습니다. 이런 경우 노드 실행시 콘솔에 로그가 남습니다. 이를 수집에서 분석하고 직접 처리할 수도 있습니다. 아니면 그냥 콘솔 출력을 어지럽히는 것을 막기 위해 그럴 수도 있죠. 이런 식으로 {{domxref("Window.unhandledrejection_event", "unhandledrejection")}}(영어) 이벤트를 처리하는 핸들러를 추가하면 됩니다.

-
window.addEventListener("unhandledrejection", event => {
+
window.addEventListener("unhandledrejection", event => {
   /* 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
 
 

이상적인 프로그래밍 세계에서는 모든 비동기 함수는 promise을 반환해야 하지만. 불행히도 일부 API는 여전히 success 및 / 또는 failure 콜백을 전달하는 방식일거라 생각합니다.. 예를 들면 {{domxref ( "WindowTimers.setTimeout", "setTimeout ()")}} 함수가 있습니다.

-
setTimeout(() => saySomething("10 seconds passed"), 10000);
+
setTimeout(() => saySomething("10 seconds passed"), 10000);
 

예전 스타일의 콜백과 Promise를 합치는것 문제가 있습니다. 함수 saySomething()이 실패하거나 프로그래밍 오류가 있으면 아무 것도 잡아 내지 않습니다. setTimeout의 문제점 입니다.

다행히도 우리는 setTimeout을 Promise로 감쌀 수 있습니다. 가장 좋은 방법은 가능한 가장 낮은 수준에서 문제가되는 함수를 래핑 한 다음 다시는 직접 호출하지 않는 것입니다.

-
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
+
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
 
 wait(10000).then(() => saySomething("10 seconds")).catch(failureCallback);
 
@@ -236,14 +236,14 @@ wait(10000).then(() => saySomething("10 seconds")).catch(failureCallback);우리는 병렬로 작업을 시작하고 모든 작업이 다음과 같이 끝날 때까지 기다릴 수 있습니다.

-
Promise.all([func1(), func2(), func3()])
+
Promise.all([func1(), func2(), func3()])
 .then(([result1, result2, result3]) => { /* use result1, result2 and result3 */ });

Sequential composition is possible using some clever JavaScript:

고급진 JavaScript를 사용하여 순차적 구성이 가능합니다.

-
[func1, func2, func3].reduce((p, f) => p.then(f), Promise.resolve())
+
[func1, func2, func3].reduce((p, f) => p.then(f), Promise.resolve())
 .then(result3 => { /* use result3 */ });
 
@@ -251,19 +251,19 @@ wait(10000).then(() => saySomething("10 seconds")).catch(failureCallback);이것은 재사용 가능한 작성 기능으로 만들 수 있는데, 이는 함수형 프로그래밍에서 일반적인 방식입니다.

-
const applyAsync = (acc,val) => acc.then(val);
+
const applyAsync = (acc,val) => acc.then(val);
 const composeAsync = (...funcs) => x => funcs.reduce(applyAsync, Promise.resolve(x));
 

composeAsync() 함수는 여러 함수를 인수로 받아들이고 composition 파이프 라인을 통해 전달되는 초기 값을 허용하는 새 함수를 반환합니다.

-
const transformData = composeAsync(func1, func2, func3);
+
const transformData = composeAsync(func1, func2, func3);
 const result3 = transformData(data);
 

ECMAScript 2017에서는 async / await를 사용하여 순차적 구성을보다 간단하게 수행 할 수 있습니다.

-
let result;
+
let result;
 for (const f of [func1, func2, func3]) {
   result = await f(result);
 }
@@ -275,13 +275,13 @@ for (const f of [func1, func2, func3]) {
 
 

놀라움(역자 주. 에러가 난다거나, 코드가 문제가 생긴다거나..했을때의 그 놀라움..)을 피하기 위해 then()에 전달 된 함수는 already-resolved promise에 있는 경우에도 동기적으로 호출되지 않습니다.

-
Promise.resolve().then(() => console.log(2));
+
Promise.resolve().then(() => console.log(2));
 console.log(1); // 1, 2
 

즉시 실행되는 대신 전달 된 함수는 마이크로 태스크 대기열에 저장됩니다. 즉, 자바 스크립트 이벤트 루프의 현재 실행이 끝날 때 대기열이 비면 나중에 실행됩니다.

-
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
+
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
 
 wait().then(() => console.log(4));
 Promise.resolve().then(() => console.log(2)).then(() => console.log(3));
@@ -299,7 +299,7 @@ console.log(1); // 1, 2, 3, 4

중첩은 catch 문 범위를 제한하는 제어 구조입니다. 특히, 중첩 된 catch는 중첩 된 범위 외부의 체인에있는 오류가 아닌 범위 및 그 이하의 오류 만 잡습니다. 올바르게 사용하면 오류 복구에서보다 정확한 결과를 얻을 수 있습니다.

-
doSomethingCritical()
+
doSomethingCritical()
 .then(result => doSomethingOptional(result)
   .then(optionalResult => doSomethingExtraNice(optionalResult))
   .catch(e => {})) // Ignore if optional stuff fails; proceed.
@@ -315,7 +315,7 @@ console.log(1); // 1, 2, 3, 4

promise chains을 작성할 때 주의해야 할 몇 가지 일반적인 실수는 다음과 같습니다. 이러한 실수 중 몇 가지는 다음 예제에서 나타납니다.

-
// Bad example! Spot 3 mistakes!
+
// 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) {
 
 

좋은 경험 법칙은 항상 약속의 사슬을 반환하거나 종결하는 것이며, 새로운 약속을 얻 자마자 즉각적으로 돌려서 물건을 평평하게하는 것입니다.

-
doSomething()
+
doSomething()
 .then(function(result) {
   return doSomethingElse(result);
 })
-- 
cgit v1.2.3-54-g00ecf