📖 전예홍, ⌈Do it! 타입스크립트 프로그래밍⌋, 이지스퍼블리싱, 2021
> npm init --y
> npm i -D typescript ts-node @types/node
> mkdir src
🔽 tsconfig.json
{
"compilerOptions": {
"downlevelIteration": true
}
}
![]() |
---|
출처: 자바스크립트 중급 강좌 #16 프로미스(Promise) - 코딩앙마 |
const getAllResolvedResult = <T>(promises: Promise<T>[]) => Promise.all(promises)
getAllResolvedResult<any>([Promise.resolve(true), Promise.resolve('hello')])
.then(result => console.log(result)) // [true, 'hello']
getAllResolvedResult<any>([Promise.reject(new Error('error')), Promise.resolve(1)])
.then(result => console.log(result)) // 호출되지 않는다
.catch(error => console.log('error:', error.message)) // error: error
import {readFilePromise} from './readFilePromise'
const readFilesAll = async (filenames: string[]) => {
return await Promise.all(
filenames.map(filename => readFilePromise(filename))
)
}
readFilesAll(['./package.json', './tsconfig.json'])
.then(([packageJson, tsconfigJson]: string[]) => {
console.log('<package.json>: ', packageJson)
console.log('<tsconfig.json>: ', tsconfigJson)
})
.catch(err => console.log('error:', err.message))
/* 실행 결과
<package.json>: {
...생략(package.json 파일 내용)...
}
<tsconfig.json>: {
...생략(tsconfig.json 파일 내용)...
}*/
동기와 비동기 방식의 차이점, resolve와 reject 함수를 매개변수로 받는 Promise의 콜백 함수 그리고 then-체인에 대해 학습했다. Promise.all 메서드와 Promise.race 메서드가 어떻게 동작하는지 이해했다. Promise를 then-체인 대신 async와 await 구문을 사용해 구현해 보았다.