From c571e6aeec49e28643beaa7b7598ed85edf0e458 Mon Sep 17 00:00:00 2001 From: Dilrong Date: Fri, 25 Jun 2021 00:22:15 +0900 Subject: async_await 번역 추가, 오탈자 수정, en-us 동기화 (#1288) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * async_await 번역 추가, 오탈자 수정, en-us 동기화 * .DS_Store 제거 * 코드 리뷰 수정 사항 반영 --- .../javascript/asynchronous/async_await/index.html | 158 ++++++++++++--------- 1 file changed, 94 insertions(+), 64 deletions(-) (limited to 'files/ko/learn/javascript/asynchronous') diff --git a/files/ko/learn/javascript/asynchronous/async_await/index.html b/files/ko/learn/javascript/asynchronous/async_await/index.html index 339a9dabdb..92a9d81dc6 100644 --- a/files/ko/learn/javascript/asynchronous/async_await/index.html +++ b/files/ko/learn/javascript/asynchronous/async_await/index.html @@ -1,34 +1,43 @@ --- -title: Making asynchronous programming easier with async and await +title: async와 await를 사용하여 비동기 프로그래밍을 쉽게 만들기 slug: Learn/JavaScript/Asynchronous/Async_await -translation_of: Learn/JavaScript/Asynchronous/Async_await +tags: + - Beginner + - CodingScripting + - Guide + - JavaScript + - Learn + - Promises + - async + - asynchronous + - await ---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Promises", "Learn/JavaScript/Asynchronous/Choosing_the_right_approach", "Learn/JavaScript/Asynchronous")}}
-

Javascript에 대한 최신 추가 사항은 ECMAScript 2017 JavaScript 에디션의 일부인 async functions 그리고 await 키워드 입니다.(ECMAScript Next support in Mozilla를 참조하세요). 이러한 기능들은 Promise기반 코드를 좀 더 쓰기 쉽고 읽기 쉽게 만들어줍니다. 이 기능을 사용하면 비동기 코드를 구식 동기 코드처럼 보여주기 때문에 충분히 배울 가치가 있습니다.이번 문서에서 위의 기능을 어떻게 사용하는지 배울 것 입니다.

+

Javascript에 대한 최신 추가 사항은 ECMAScript 2017 JavaScript 에디션의 일부인 async functions 그리고 await 키워드는 ECMAScript2017에 추가되었습니다. 이 기능들은 기본적으로 비동기 코드를 쓰고 Promise를 더 읽기 더 쉽도록 만들어줍니다. 비동식 코드는 구식 동기코드를 읽기 쉽게 만들기 때문에 학습할 가치가 있습니다. 이 글은 당신이 비동기에 알아야할 것을 알려줍니다.

- - + + - - + +
Prerequisites:Basic computer literacy, a reasonable understanding of JavaScript fundamentals, an understanding of async code in general and promises.필수조건:기본 컴퓨터 사용능력, 자바스크립트 기초, 비동기코드에 대한 이해
Objective:To understand promises and how to use them.목표:async/await에 대한 이해
-

The basics of async/await

+

async/await의 기초

async/await 코드는 두 가지 부분으로 나눠져있습니다.

-

The async keyword

+

비동기 키워드

-

먼저 비 동기 함수를 async function으로 만들기 위하여 function()앞에 async keyword를 추가합니다. async function()은 await 키워드가 비동기 코드를 호출할 수 있게 해주는 함수 입니다.

+

먼저 비동기 함수를 async 함수로 만들기 위하여 function()앞에 async 키워드를 추가합니다. async function()은 await 키워드가 비동기 코드를 호출할 수 있게 해주는 함수 입니다.

브라우저의 JavaScript 콘솔에서 아래와 같이 입력해보세요. :

@@ -59,7 +68,7 @@ hello();
hello().then((value) => console.log(value))
-

짧개 표현하면 아래와 같이 쓸 수 있습니다.

+

짧게 표현하면 아래와 같이 쓸 수 있습니다.

hello().then(console.log)
@@ -67,7 +76,7 @@ hello();

정리하면, async 를 함수와 같이 사용하면 결과를 직접 반환하는게 아니라 Promise를 반환하게 합니다. 또한 동기식 함수는 await사용을 위한 지원과 함께 실행되는 잠재적인 오버헤드를 피할 수 있습니다. 함수가  async라고 선언될 때 필요한 핸들링만 추가하면 JavaScript엔진이 우리가 만든 프로그램을 최적화 할 수 있습니다. 끝내주죠?

-

The await keyword

+

비동기 키워드

비동기 함수를 await 키워드와 함께 쓰면 그 장점이 확실히 보입니다. 이것은 어떠한 Promise기반 함수 앞에 놓을 수 있습니다. 그리고 우리의 코드의 Promise가 fulfil될 때 까지 잠시 중단하고, 결과를 반환합니다. 그리고 실행을 기다리는 다른 코드들을 중지시키지 않고 그대로 실행되게 합니다.

@@ -83,7 +92,7 @@ hello().then(alert);

물론 위의 예시는 그다지 쓸모있진 않습니다. 다만 어떻게 구문을 작성해야 하는지는 잘 나타내줍니다. 이제 실제 사례를 살펴봅시다.

-

Rewriting promise code with async/await

+

async/await와 함께 다시 쓰는 promise code

이전 문서에서 봤던 간단한 fetch() 예제를 살펴봅시다. :

@@ -122,7 +131,11 @@ myFetch()
async function myFetch() {
   let response = await fetch('coffee.jpg');
-  return await response.blob();
+  if (!response.ok) {
+    throw new Error(`HTTP error! status: ${response.status}`);
+  }
+  return await response.blob();
+
 }
 
 myFetch().then((blob) => {
@@ -132,27 +145,23 @@ myFetch().then((blob) => {
   document.body.appendChild(image);
 }).catch(e => console.log(e));
-

예제를 직접 만들어보거나, 여기서 결과를 확인할 수 있습니다. live example (see also the source code).

+

예제를 직접 만들어보거나, 여기서 결과를 확인할 수 있습니다. 예제 (여기서 소스코드를 볼 수 있습니다.).

-

But how does it work?

+

어떻게 작동할까요?

함수 안에 코드를 작성했고, function 키워드 앞에 async 키워드를 썼다는 것을 알 수 있습니다. 꼭 이렇게 써야합니다!! 비동기 코드를 실행할 블럭을 정의하려면 비동기 함수를 생성해야 합니다. awaitasync function 안에서만 쓸 수 있습니다.

-
-

Note: It's worth saying again, in a box with an eye-catching background color: await only works inside async functions.

-
-

myFetch() 함수 내에 코드가 이전의 Promise버전과 매우 유사하지만, 다른점이 있습니다. .then()블럭을 사용하여 작업을 이어가는 대신 메서드 호출 전에 await 키워드를 사용하여 반환된 결과를 변수에 할당합니다. await 키워드는 JavaScript 런타임이 이 라인에서 비동기 코드를 일시 중지하여 비동기 함수 호출이 결과를 반환할 때 까지 기다리게 합니다. 그러나 외부의 다른 동기 코드는 실행될 수 있도록 합니다. 작업이 완료되면 코드는 계속 이어져서 실행됩니다. 예를들면 아래와 같습니다. :

let response = await fetch('coffee.jpg');
-

fullfilled된 fetch() Promise에서 반환된 응답은 해당 응답이 사용할 수 있게 되면 response 변수에 할당됩니다. 그리고 parser는 해당 응답이 발생할 때 까지 이 라인에서 일시 중지됩니다. response가 사용 가능하게 되면, parser 는 다음 라인으로 이동하게 되고 그 라인에서 Blob 을 생성하게 됩니다. 이라인도 Promise기반 비동기 메서드를 호출하므로, 여기서도await 을 사용합니다. 비동기 작업 결과가 반환되면, myFetch() 함수가 그 결과를 반환합니다.

+

fulfilled된 fetch() Promise에서 반환된 응답은 해당 응답이 사용할 수 있게 되면 response 변수에 할당됩니다. 그리고 parser는 해당 응답이 발생할 때 까지 이 라인에서 일시 중지됩니다. response가 사용 가능하게 되면, parser 는 다음 라인으로 이동하게 되고 그 라인에서 Blob 을 생성하게 됩니다. 이라인도 Promise기반 비동기 메서드를 호출하므로, 여기서도await 을 사용합니다. 비동기 작업 결과가 반환되면, myFetch() 함수가 그 결과를 반환합니다.

myFetch() 함수를 호출하면, Promise를 반환하므로, 따라서 화면에 Blob을 표시해주는 .then() 코드 블럭 체이닝 할 수 있습니다.

여기까지 왔으면 이 방법이 멋있다고 생각해야합니다! 왜냐하면 .then() 블럭이 줄어들고 대부분이 동기 코드처럼 보이기 때문에 정말 직관적입니다.

-

Adding error handling

+

오류 처리 추가

그리고 오류 처리를 하려면 몇 가지 옵션이 있습니다.

@@ -161,12 +170,16 @@ myFetch().then((blob) => {
async function myFetch() {
   try {
     let response = await fetch('coffee.jpg');
-    let myBlob = await response.blob();
 
-    let objectURL = URL.createObjectURL(myBlob);
-    let image = document.createElement('img');
-    image.src = objectURL;
-    document.body.appendChild(image);
+    if (!response.ok) {
+      throw new Error(`HTTP error! status: ${response.status}`);
+    }
+    let myBlob = await response.blob();
+    let objectURL = URL.createObjectURL(myBlob);
+    let image = document.createElement('img');
+    image.src = objectURL;
+    document.body.appendChild(image);
+
   } catch(e) {
     console.log(e);
   }
@@ -180,7 +193,11 @@ myFetch();
async function myFetch() {
   let response = await fetch('coffee.jpg');
-  return await response.blob();
+  if (!response.ok) {
+    throw new Error(`HTTP error! status: ${response.status}`);
+  }
+  return await response.blob();
+
 }
 
 myFetch().then((blob) => {
@@ -198,28 +215,34 @@ myFetch().then((blob) => {
 

위의 예제 모두를 GitHub에서 찾아볼 수 있습니다. :

Awaiting a Promise.all()

-

async/await는 promises의 상위에 만들어져 있기 때문에 Promise의 모든 기능을 사용할 수 있습니다. Promise.all() 을 포함해서 말이죠 — 아래 보이는 코드처럼 Promise.all() 앞에 async키워드를 사용하여 동기식 코드처럼 작성할 수 있습니다. 이전 문서를 확인해봅시다. an example we saw in our previous article. 새로운 버전과 비교하기 위해 탭을 분리 해보세요.

+

async/await는 promises의 상위에 만들어져 있기 때문에 Promise의 모든 기능을 사용할 수 있습니다. Promise.all() 을 포함해서 말이죠 — 아래 보이는 코드처럼 Promise.all() 앞에 async키워드를 사용하여 동기식 코드처럼 작성할 수 있습니다. 이전 문서를 확인해봅시다. 이전에 글에서 본 예제. 새로운 버전과 비교하기 위해 탭을 분리 해보세요.

-

Aasync/await 스타일로 변경한 코드는 아래와 같습니다. (see live demo and source code) :

+

async/await 스타일로 변경한 코드는 아래와 같습니다. (데모 그리고 소스 코드) :

async function fetchAndDecode(url, type) {
   let response = await fetch(url);
 
   let content;
 
-  if(type === 'blob') {
-    content = await response.blob();
-  } else if(type === 'text') {
-    content = await response.text();
+  if (!response.ok) {
+    throw new Error(`HTTP error! status: ${response.status}`);
+  } else {
+    if(type === 'blob') {
+      content = await response.blob();
+    } else if(type === 'text') {
+      content = await response.text();
+    }
   }
 
   return content;
+
+
 }
 
 async function displayContent() {
@@ -247,7 +270,7 @@ async function displayContent() {
 
 displayContent()
 .catch((e) =>
-  console.log(e)
+  console.log(e)
 );

몇 가지 사항을 조금 수정했을 뿐인데 fetchAndDecode()함수를 쉽게 비동기 함수로 변환했습니다. Promise.all() 라인을 살펴보세요:

@@ -259,12 +282,12 @@ displayContent()

마지막으로 에러를 다루기 위해 .catch() 블럭을 displayContent() 함수를 호출하는 곳에 추가했습니다. 이렇게 하면 두 함수에서 발생하는 에러를 처리할 수 있습니다.

-

Note: It is also possible to use a sync finally block within an async function, in place of a .finally() async block, to show a final report on how the operation went — you can see this in action in our live example (see also the source code).

+

Note: finally비동기 블록 대신 비동기 함수 내에서 .finally() 동기 블록을 사용하여 작업이 어떻게 진행되었는지에 대한 최종 보고서를 표시할 수 있습니다. 예제에서도 확인이 가능합니다. 소스 코드).

-

The downsides of async/await

+

async/await의 단점

-

앞서 봤듯이 async/await 은매우 유용하지만 고려해야 할 몇 가지 단점이 있습니다.

+

앞서 봤듯이 async/await은 매우 유용하지만 고려해야 할 몇 가지 단점이 있습니다.

Async/await 는 우리의 코드를 마치 동기식 코드처럼 보이게 합니다. 그리고 어떤 면에서는 정말로 동기적으로 행동합니다. 함수 블럭에 여러 개의 await 키워드를 사용하면 Promise가 fulfilled되기 전 까지 다음 await 을 차단합니다. 그 동안 다른 태스크는 계속 실행이 되지만 정의한 함수 내에서는 동기적으로 작동할 것 입니다.

@@ -272,15 +295,21 @@ displayContent()

이 문제를 완화할 수 있는 패턴이 있습니다. — 모든 Promise 오브젝트를 변수에 저장하여 미리 실행되게 하고 변수가 사용 가능할 때 꺼내서 쓰는 것 입니다. 어떻게 작동하는지 한번 살펴봅시다.

-

두 가지 예시를 보여주겠습니다. — 느린 비동기 작업 slow-async-await.html (see source code) 그리고 빠른 비동기 작업 fast-async-await.html (see source code)입니다. 두 예제에서  마치 비동기 작업인 것 처럼 보이기 위해 setTimeout() 을 사용했습니다. :

- -
function timeoutPromise(interval) {
-  return new Promise((resolve, reject) => {
-    setTimeout(function(){
-      resolve("done");
-    }, interval);
-  });
-};
+

두 가지 예시를 보여 드리겠습니다. — 느린 비동기 작업 slow-async-await.html (소스 코드) 그리고 빠른 비동기 작업 fast-async-await.html (소스 코드)입니다. 두 예제에서 마치 비동기 작업인 것 처럼 보이기 위해 setTimeout() 을 사용했습니다. :

+ +
async function makeResult(items) {
+   let newArr = [];
+   for(let i=0; i < items.length; i++) {
+     newArr.push('word_'+i);
+   }
+   return newArr;
+ }
+ 
+ async function getResult() {
+   let result = await makeResult(items); // Blocked on this line
+   useThatResult(result); // Will not be executed before makeResult() is done
+ }
+ 

그리고 세 가지 timeoutPromise() 함수를 호출하는 timeTest()함수를 만들었습니다.

@@ -329,9 +358,9 @@ timeTest().then(() => {

다른 아주 사소한 단점은 비동기로 실행될 Promise가 있다면 async함수 안에 항상 await을 써야한다는 것 입니다.

-

Async/await class methods

+

Async/await class 메서드

-

마지막으로 보여줄 내용은 async 키워드를 class/object의 메서드에 사용하여 Promise를 반환하게 만들 수 있다는 것 입니다. 그리고 await 를 그 안에 넣을 수도 있습니다. 다음 문서를 살펴보세요 > ES class code we saw in our object-oriented JavaScript article, 그리고 보이는 코드를async 메서드로 수정한 아래의 내용과 비교 해보세요 :

+

마지막으로 보여줄 내용은 async 키워드를 class/object의 메서드에 사용하여 Promise를 반환하게 만들 수 있다는 것 입니다. 그리고 await 를 그 안에 넣을 수도 있습니다. 다음 문서를 살펴보세요 > ES class code we saw in our object-oriented JavaScript article, 그리고 보이는 코드를 async 메서드로 수정한 아래의 내용과 비교 해보세요 :

class Person {
   constructor(first, last, age, gender, interests) {
@@ -359,25 +388,26 @@ let han = new Person('Han', 'Solo', 25, 'male', ['Smuggling']);
han.greeting().then(console.log);
-

Browser support

+

브라우저 지원

-

One consideration when deciding whether to use async/await is support for older browsers. They are available in modern versions of most browsers, the same as promises; the main support problems come with Internet Explorer and Opera Mini.

+

async/await 사용 여부를 결정할 때 고려해야 할 한가지 사항은 이전 브라우저에 대한 지원입니다. + promises와 마찬가지로 대부분의 최신 브라우저에서 사용할 수 있습니다. + 주요 지원 문제는 Internet Explorer 그리고 Opera Mini에서 발생합니다.

-

If you want to use async/await but are concerned about older browser support, you could consider using the BabelJS library — this allows you to write your applications using the latest JavaScript and let Babel figure out what changes if any are needed for your user’s browsers. On encountering a browser that does not support async/await, Babel's polyfill can automatically provide fallbacks that work in older browsers.

+

async/await을 사용하는데 브라우저 지원이 걱정되는 경우 BabelJS 라이브러리를 사용하는 것을 고려해 볼 수 있습니다. BabelJS는 최신 자바스크립트를 사용하여 애플리케이션을 작성하고 사용자 브라우저에 필요한 변경사항을 Babel이 파악할 수 있도록 지원합니다. async/await를 지원하지 않는 브라우저를 만나면 Babel은 이전 브라우저에서 작동하는 polyfill를 자동으로 제공합니다.

-

Conclusion

+

결론

-

And there you have it — async/await provide a nice, simplified way to write async code that is simpler to read and maintain. Even with browser support being more limited than other async code mechanisms at the time of writing, it is well worth learning and considering for use, both for now and in the future.

+

async/await를 사용하면 읽기 쉽고 유지보수가 편리한 비동기 코드를 간단하게 작성할 수 있습니다. 브라우저 지원이 다른 비동기 코드에 비해 제한적이기는 하지만 현재는 물론 미래에도 사용을 위해 배울 가치는 충분합니다.

{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Promises", "Learn/JavaScript/Asynchronous/Choosing_the_right_approach", "Learn/JavaScript/Asynchronous")}}

-

In this module

+

이 모듈에서

+
  • General asynchronous programming concepts
  • +
  • Introducing asynchronous JavaScript
  • +
  • Cooperative asynchronous JavaScript: Timeouts and intervals
  • +
  • Graceful asynchronous programming with Promises
  • +
  • Choosing the right approach
  • + -- cgit v1.2.3-54-g00ecf