Skip to content

translate Async Await.ts, Optional Chaining.ts to ko #1077

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 20, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
//// { compiler: { }, order: 1 }

// 선택적 체이닝(Optional chaining)이 TC39 3단계에서 합의점에 도달했습니다.
// 그것이 TS 3.7 내용입니다. 선택적 체이닝을 사용하면
// null 또는 undefined인 코드에 도달했을 때
// 즉시 중지할 수 있는 코드를 작성할 수 있습니다.

// 프로퍼티 접근 (Property Access)

// 우리가 아티스트와 아티스트 약력이 없는
// 앨범을 가지고 있다고 가정해 보겠습니다. 예를 들면,
// 컴필레이션 앨범에는 아티스트 정보가 없습니다.

type AlbumAPIResponse = {
title: string;
artist?: {
name: string;
bio?: string;
previousAlbums?: string[];
};
};

declare const album: AlbumAPIResponse;

// 선택적 체이닝을 사용하면,
// 다음과 같은 코드를 작성할 수 있습니다:

const artistBio = album?.artist?.bio;

// 대신에:

const maybeArtistBio = album.artist && album.artist.bio;

// 이 경우 ?.는 &&과는 다르게 동작합니다. 왜냐하면,
// &&는 "falsy" 값에 대한 동작이 다르기 때문입니다.
// (예. 빈 문자열, 0, NaN, 그리고, false).

// 선택적 체이닝은 null이거나 undefined이면
// 동작을 멈추고, undefined를 반환합니다.

// 선택적 요소 접근 (Optional Element Access)

// 프로퍼티 접근은 .연산자만을 이용하고,
// 선택적 체이닝이 요소에 접근할 때는 []연산자와 함께 이용합니다.

const maybeArtistBioElement = album?.["artist"]?.["bio"];

const maybeFirstPreviousAlbum = album?.artist?.previousAlbums?.[0];

// 선택적 호출(Optional Calls)

// 런타임 시 존재 여부를 판단하는 함수를 다룰 때,
// 선택적 체이닝은 실제로 존재하는 경우에만 함수호출을 지원합니다.
// 이는 if (func) func()과 같은 기존에 사용하던 코드를
// 대체할 수 있습니다.

// 예를 들어 API 요청에 의한 콜백 함수의 선택적 호출은
// 다음과 같습니다:

const callUpdateMetadata = (metadata: any) => Promise.resolve(metadata); // Fake API call

const updateAlbumMetadata = async (metadata: any, callback?: () => void) => {
await callUpdateMetadata(metadata);

callback?.();
};

// 선택적 체이닝에 대한 자세한 내용은 3.7 블로그 게시물을 통해 확인할 수 있습니다:
//
// https://devblogs.microsoft.com/typescript/announcing-typescript-3-7/
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
//// { order: 1, target: "es5" }

// 모던 JavaScript는 특별한 구문의
// 프로미스(Promise) 기반 API를 추가하여
// 비동기 코드가 동기적으로 작동하는 것처럼
// 콜백을 처리하는 방법을 추가했습니다.

// 모든 언어 기능과 마찬가지로, 이러한 방식은 복잡성이 증가하는 대신 효율성이
// 증가합니다: 함수를 async로 만드는 것은 반환값을 프로미스 형태로
// 감싸주는 것을 의미합니다. 기존에는 string을 반환했지만
// 이제 Promise<string>을 반환합니다.

const func = () => ":wave:";
const asyncFunc = async () => ":wave:";

const myString = func();
const myPromiseString = asyncFunc();

myString.length;

// myPromiseString은 string이 아닌 프로미스 입니다:

myPromiseString.length;

// await 키워드를 사용하면 프로미스를 내부의 값으로 변환할 수 있습니다.
// 현재, 이러한 기능은 async 함수 내에서만
// 작동합니다.

const myWrapperFunction = async () => {
const myString = func();
const myResolvedPromiseString = await asyncFunc();

// await 키워드를 통해, 이제 myResolvedPromiseString
// 값은 문자열입니다.
myString.length;
myResolvedPromiseString.length;
};

// await을 통해 실행되는 코드는 오류 객체를 발생시킬 수 있고,
// 이러한 오류를 잡아내는 것이 중요합니다.

const myThrowingFunction = async () => {
throw new Error("Do not call this");
};

// async 함수를 try catch 문으로 감싸
// 함수가 예기치 않게 작동하는 경우를 처리합니다.

const asyncFunctionCatching = async () => {
const myReturnValue = "Hello world";
try {
await myThrowingFunction();
} catch (error) {
console.error("myThrowingFunction failed", error);
}
return myReturnValue;
};

// 단일 값을 반환하거나 오류를 발생시키는
// API의 인간 공학적 특성 때문에,
// 반환 값 내부의 결괏값에 대한 정보 제공을 고려해야 하며,
// 실제 예외적인 상황이 발생했을 때만
// throw 문을 사용해야 합니다.

const exampleSquareRootFunction = async (input: any) => {
if (isNaN(input)) {
throw new Error("Only numbers are accepted");
}

if (input < 0) {
return { success: false, message: "Cannot square root negative number" };
} else {
return { success: true, value: Math.sqrt(input) };
}
};

// 그런 다음 해당 비동기 함수를 받는 객체로 응답 상태를 확인하고
// 반환 값으로 무엇을 처리할지 알아냅니다.
// 이것은 사소한 예제지만, 네트워킹 코드를 작업을 시작하면
// 이러한 API는 구문은 추가할만한 가치가 있습니다.

const checkSquareRoot = async (value: number) => {
const response = await exampleSquareRootFunction(value);
if (response.success) {
response.value;
}
};

// Async/Await 구문은 다음과 같은 코드를 사용해왔습니다:

// getResponse(url, (response) => {
// getResponse(response.url, (secondResponse) => {
// const responseData = secondResponse.data
// getResponse(responseData.url, (thirdResponse) => {
// ...
// })
// })
// })

// 이를 순차적으로 작성하면:

// const response = await getResponse(url)
// const secondResponse = await getResponse(response.url)
// const responseData = secondResponse.data
// const thirdResponse = await getResponse(responseData.url)
// ...

// 코드가 왼쪽 가장자리에 가깝게 배치되어,
// 코드가 일관된 리듬으로 읽힐 수 있습니다.
2 changes: 1 addition & 1 deletion packages/playground-examples/copy/ko/sections.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,4 @@
"New TS Features",
"New Checks"
]
}
}