|
| 1 | +//// { order: 1, target: "es5" } |
| 2 | + |
| 3 | +// 모던 JavaScript는 특별한 구문의 |
| 4 | +// 프로미스(Promise) 기반 API를 추가하여 |
| 5 | +// 비동기 코드가 동기적으로 작동하는 것처럼 |
| 6 | +// 콜백을 처리하는 방법을 추가했습니다. |
| 7 | + |
| 8 | +// 모든 언어 기능과 마찬가지로, 이러한 방식은 복잡성이 증가하는 대신 효율성이 |
| 9 | +// 증가합니다: 함수를 async로 만드는 것은 반환값을 프로미스 형태로 |
| 10 | +// 감싸주는 것을 의미합니다. 기존에는 string을 반환했지만 |
| 11 | +// 이제 Promise<string>을 반환합니다. |
| 12 | + |
| 13 | +const func = () => ":wave:"; |
| 14 | +const asyncFunc = async () => ":wave:"; |
| 15 | + |
| 16 | +const myString = func(); |
| 17 | +const myPromiseString = asyncFunc(); |
| 18 | + |
| 19 | +myString.length; |
| 20 | + |
| 21 | +// myPromiseString은 string이 아닌 프로미스 입니다: |
| 22 | + |
| 23 | +myPromiseString.length; |
| 24 | + |
| 25 | +// await 키워드를 사용하면 프로미스를 내부의 값으로 변환할 수 있습니다. |
| 26 | +// 현재, 이러한 기능은 async 함수 내에서만 |
| 27 | +// 작동합니다. |
| 28 | + |
| 29 | +const myWrapperFunction = async () => { |
| 30 | + const myString = func(); |
| 31 | + const myResolvedPromiseString = await asyncFunc(); |
| 32 | + |
| 33 | + // await 키워드를 통해, 이제 myResolvedPromiseString |
| 34 | + // 값은 문자열입니다. |
| 35 | + myString.length; |
| 36 | + myResolvedPromiseString.length; |
| 37 | +}; |
| 38 | + |
| 39 | +// await을 통해 실행되는 코드는 오류 객체를 발생시킬 수 있고, |
| 40 | +// 이러한 오류를 잡아내는 것이 중요합니다. |
| 41 | + |
| 42 | +const myThrowingFunction = async () => { |
| 43 | + throw new Error("Do not call this"); |
| 44 | +}; |
| 45 | + |
| 46 | +// async 함수를 try catch 문으로 감싸 |
| 47 | +// 함수가 예기치 않게 작동하는 경우를 처리합니다. |
| 48 | + |
| 49 | +const asyncFunctionCatching = async () => { |
| 50 | + const myReturnValue = "Hello world"; |
| 51 | + try { |
| 52 | + await myThrowingFunction(); |
| 53 | + } catch (error) { |
| 54 | + console.error("myThrowingFunction failed", error); |
| 55 | + } |
| 56 | + return myReturnValue; |
| 57 | +}; |
| 58 | + |
| 59 | +// 단일 값을 반환하거나 오류를 발생시키는 |
| 60 | +// API의 인간 공학적 특성 때문에, |
| 61 | +// 반환 값 내부의 결괏값에 대한 정보 제공을 고려해야 하며, |
| 62 | +// 실제 예외적인 상황이 발생했을 때만 |
| 63 | +// throw 문을 사용해야 합니다. |
| 64 | + |
| 65 | +const exampleSquareRootFunction = async (input: any) => { |
| 66 | + if (isNaN(input)) { |
| 67 | + throw new Error("Only numbers are accepted"); |
| 68 | + } |
| 69 | + |
| 70 | + if (input < 0) { |
| 71 | + return { success: false, message: "Cannot square root negative number" }; |
| 72 | + } else { |
| 73 | + return { success: true, value: Math.sqrt(input) }; |
| 74 | + } |
| 75 | +}; |
| 76 | + |
| 77 | +// 그런 다음 해당 비동기 함수를 받는 객체로 응답 상태를 확인하고 |
| 78 | +// 반환 값으로 무엇을 처리할지 알아냅니다. |
| 79 | +// 이것은 사소한 예제지만, 네트워킹 코드를 작업을 시작하면 |
| 80 | +// 이러한 API는 구문은 추가할만한 가치가 있습니다. |
| 81 | + |
| 82 | +const checkSquareRoot = async (value: number) => { |
| 83 | + const response = await exampleSquareRootFunction(value); |
| 84 | + if (response.success) { |
| 85 | + response.value; |
| 86 | + } |
| 87 | +}; |
| 88 | + |
| 89 | +// Async/Await 구문은 다음과 같은 코드를 사용해왔습니다: |
| 90 | + |
| 91 | +// getResponse(url, (response) => { |
| 92 | +// getResponse(response.url, (secondResponse) => { |
| 93 | +// const responseData = secondResponse.data |
| 94 | +// getResponse(responseData.url, (thirdResponse) => { |
| 95 | +// ... |
| 96 | +// }) |
| 97 | +// }) |
| 98 | +// }) |
| 99 | + |
| 100 | +// 이를 순차적으로 작성하면: |
| 101 | + |
| 102 | +// const response = await getResponse(url) |
| 103 | +// const secondResponse = await getResponse(response.url) |
| 104 | +// const responseData = secondResponse.data |
| 105 | +// const thirdResponse = await getResponse(responseData.url) |
| 106 | +// ... |
| 107 | + |
| 108 | +// 코드가 왼쪽 가장자리에 가깝게 배치되어, |
| 109 | +// 코드가 일관된 리듬으로 읽힐 수 있습니다. |
0 commit comments