Typescript/러닝 타입스크립트 연습문제

(1장) The Typeinator - 3. Callbacks to Async Await

띵킹 2023. 4. 5. 21:54

 

 

https://github.com/LearningTypeScript/projects/tree/main//projects/from-javascript-to-typescript/the-typeinator/03-callbacks-to-async-await

 

GitHub - LearningTypeScript/projects: Hands-on real world projects that will help you exercise your knowledge of TypeScript.

Hands-on real world projects that will help you exercise your knowledge of TypeScript. - GitHub - LearningTypeScript/projects: Hands-on real world projects that will help you exercise your knowledg...

github.com

 

original.js 파일에는 checkEmotion 및 speak 함수에 대한 프로젝트의 원본 코드가 포함되어 있습니다. 
이 함수들은 이전의 Node.js 스타일의 콜백 파라미터로 작성되어 있습니다. 
귀하의 임무는 해당 코드를 적절한 ES2017+ async/await로 포팅하는 것입니다.

## 명세
index.js에서 두 개의 async 함수를 내보냅니다.

checkEmotion : original.js의 checkEmotion 함수를 기반으로 하는 함수
speak : original.js의 speak 함수를 기반으로 하는 함수

## 파일
index.js: checkEmotion, speak 함수를 작성할 곳
index.test.js: checkEmotion 및 speak 확인 테스트
solution.js: 솔루션 코드
function checkEmotion(knownEmotions, emotion, callback) {
	// Simulate database processing time by waiting a second...
	setTimeout(() => {
		callback(knownEmotions.has(emotion));
	}, 1000);
}

function speak(knownEmotions, newEmotion, phrase, callback) {
	checkEmotion(knownEmotions, newEmotion, (hasEmotion) => {
		if (hasEmotion) {
			callback(`"${phrase}" (${newEmotion})`);
		} else {
			callback(
				undefined,
				new Error(`Does not compute. I do not understand ${newEmotion}.`)
			);
		}
	});
}

오리지널 코드의 checkEmotion 함수는 db 처리를 시뮬레이션 하기 위해 의도적으로 timeout을 실행한다. 

지연 이후에 콜백함수에 knownEmotions 자료구조에 emotion의 존재 여부를 전달해준다.

spaek 함수는 checkEmotion의 실행 여부에 따라 콜백함수를 호출하거나 에러를 만든다.

const checkEmotion = async (knownEmotions, emotion) => {
    await new Promise((reslove) => {
        setTimeout(reslove, 1000);
    })
    return knownEmotions.has(emotion)
}

const speak = async (knownEmotions, newEmotion, phrase) => {
    const hasEmotion = await checkEmotion(knownEmotions, newEmotion)
    if(!hasEmotion) {
        throw new Error(`Does not compute. I do not understand ${newEmotion}.`)
    }
    return `"${phrase}" (${newEmotion})`
}


module.exports.checkEmotion = checkEmotion;
module.exports.speak = speak;

 

async await를 통해 구현한 코드.

 

 

728x90