Promise는 비동기 코드를 관리할 수 있도록 도와주고, 많은 써드파티 라이브러리나 DOM API에서 활용됩니다. 비동기 함수(Async/await)는 Promise를 다루는 특별한 문법으로 Promise와 함께 사용됩니다.
export const timeout = (duration = 0, shouldReject = false) => { return new Promise((resolve, reject) => { setTimeout(() => { if (shouldReject) { reject(`${duration}ms 후, 거절 처리 됨.`) } else { resolve(`${duration}ms 후, 승인 처리 됨.`) } }, duration) }) } export const log = (...args) => console.log(...args) export const logError = (...args) => console.error(...args)
import { timeout, log, logError } from './utils.js' // 성공 예 const success = timeout(1000).then(success => `성공: ${success}`) // 실패 예 const fail = timeout(1000, true).then( null, error => Promise.reject(`실패: ${error}`) ) // 실패 → 복구 예 const recovered = timeout(1000, true).then( null, error => Promise.resolve(`실패 → 복구: ${error}`) ) success.then(log, logError) fail.then(log, logError) recovered.then(log, logError)
Last updated 4 years ago
Was this helpful?