과거 프로그래밍 자료들/Javascript&typescript
[TS] Promise, Awaited
평부
2022. 9. 20. 14:35
출처 : https://github.com/ZeroCho/ts-all-in-one
출처 : https://github.com/microsoft/TypeScript/blob/main/lib/lib.es5.d.ts
출처(Promise): https://github.com/microsoft/TypeScript/blob/main/lib/lib.es2015.promise.d.ts
* [lib.es2015.promise.d.ts] Promise & [lib.ex5.d.ts] Awaited
all<T extends readonly unknown[] | []>(values: T): Promise<{ readonly [P in keyof T]: Awaited<T[P]> }>
type Awaited<T> =
T extends null | undefined ? T : // special case for `null | undefined` when not in `--strictNullChecks` mode
T extends object & { then(onfulfilled: infer F): any } ? // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped
F extends ((value: infer V, ...args: any) => any) ? // if the argument to `then` is callable, extracts the first argument
Awaited<V> : // recursively unwrap the value
never : // the argument to `then` was not callable
T; // non-object or non-thenable
* Promise.all의 결과는 왜 배열로 나올까?
const p1 = Promise.resolve(1).then((a) => a + 1).then((a) => a + 1).then((a) => a.toString());
const p2 = Promise.resolve(2);
const p3 = new Promise((res, rej) => {
setTimeout(res, 1000);
})
Promise.all([p1, p2, p3]).then((result) => {
console.log(result); //result의 값을 수정할 수 있음
//결과(배열이 나옴) ['0': string, '1': number, '2': unknown, length: 3]
})
* 해설
▶ (p1) Await<T> : Promise<string>의 V는 string => Awaited<string> => string
▶ (p2) Await<T> : Promise<number>의 V는 number => Awaited<number> => number
▶ (p3) Await<T> : Promise<unknown>의 V는 unknown=> Awaited<unknown> => unknown
//p1은 문자열 '3'이 나옴(toString)
const p1 = Promise.resolve(1).then((a) => a + 1).then((a) => a + 1).then((a) => a.toString());
//p1 => Promise<number>, Promise<number>, Promise<number>, Promise<string>
const p2 = Promise.resolve(2);
//p2 => Promise<number>
const p3 = new Promise((res, rej) => {//p3 => Primise<unknown>
setTimeout(res, 1000);
})
//all<T extends readonly unknown[] | []>(values: T): Promise<{ readonly [P in keyof T]: Awaited<T[P]> }> //P는 배열의 값
//T = [p1, p2, p3] (프로미스 = 객체(object))
//keyof T = '0' | '1' | '2' | 'length'
Promise.all([p1, p2, p3]).then((result) => { //result도 배열
//p1, p2, p3를 수정할 수는 없는데(readonly 때문)
console.log(result); //result의 값을 수정할 수 있음
//결과(배열이 나옴) ['0': string, '1': number, '2': unknown, length: 3]
})
//keyof 관련 예제
// const arr = [1, 2, 3] as const
// type Arr = keyof typeof arr;
// const key: Arr = '100'; //오류남
type Awaited<T> =
T extends null | undefined ? T : // special case for `null | undefined` when not in `--strictNullChecks` mode
T extends object & { then(onfulfilled: infer F): any } ? // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped
F extends ((value: infer V, ...args: any) => any) ? // if the argument to `then` is callable, extracts the first argument
Awaited<V> : // recursively unwrap the value
never : // the argument to `then` was not callable
T; // non-object or non-thenable
//Await<V> :재귀, 위의 infer F는 onfulfilled
//const p1에서 a는 1 즉 타입은 number
//따라서 Await<number>로 되서 Await<T>로 돌아감
//Await<T> : Promise<string>의 V는 string => Awaited<string> => string
//Await<T> : Promise<number>의 V는 number => Awaited<number> => number
//then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
//위의 then의 매개변수 : (onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null)
//위의 then의 리턴값은 Promise<TResult1 | TResult2>
* 중첩된 Promise 예제, thenable 예제
const p1 = Promise.resolve(1).then((a) => a + 1).then((a) => a + 1).then((a) => a.toString());
const p2 = Promise.resolve(2);
const p3 = new Promise((res, rej) => {//p3 => Primise<unknown>
setTimeout(res, 1000);
})
//type Result = number
//중첩된 Promise일 경우 전부 풀어서 Promise가 아닌 최종타입으로 나옴
type Result = Awaited<Promise<Promise<Promise<number>>>>
//thenable, type Result2 = number
type Result2 = Awaited<{then(onfulfilled: (v: number) => number): any}>