본문 바로가기
코딩테스트 준비

Promise 문제 목록

by haries 2025. 11. 24.

1. Promise.race

문제 URL : https://leetcode.com/problems/promise-time-limit/

문제 유형 : Promise 비동기 처리

문제 설명

비동기 함수 fn과 시간 제한 t(밀리초)가 주어졌을 때, 시간 제한이 적용된 새로운 함수를 반환해야합니당

  • fn이 t 밀리초 내에 완료되면 → 결과를 resolve
  • fn이 t 밀리초를 초과하면 → "Time Limit Exceeded"로 reject

접근 방법

두 개의 Promise 중 먼저 끝나는 것을 결과로 return하는 것이 중요합니다.

해결방법

Input/Output 예시

Example 1:
Input: 
fn = async (n) => { 
  await new Promise(res => setTimeout(res, 100)); 
  return n * n; 
}
inputs = [5]
t = 50
Output: {"rejected":"Time Limit Exceeded","time":50}
Explanation:
const limited = timeLimit(fn, t)
const start = performance.now()
let result;
try {
   const res = await limited(...inputs)
   result = {"resolved": res, "time": Math.floor(performance.now() - start)};
} catch (err) {
   result = {"rejected": err, "time": Math.floor(performance.now() - start)};
}
console.log(result) // Output

The provided function is set to resolve after 100ms. However, the time limit is set to 50ms. It rejects at t=50ms because the time limit was reached.




Example 2:
Input: 
fn = async (n) => { 
  await new Promise(res => setTimeout(res, 100)); 
  return n * n; 
}
inputs = [5]
t = 150
Output: {"resolved":25,"time":100}
Explanation:
The function resolved 5 * 5 = 25 at t=100ms. The time limit is never reached.




Example 3:
Input: 
fn = async (a, b) => { 
  await new Promise(res => setTimeout(res, 120)); 
  return a + b; 
}
inputs = [5,10]
t = 150
Output: {"resolved":15,"time":120}
Explanation:
​​​​The function resolved 5 + 10 = 15 at t=120ms. The time limit is never reached.




Example 4:
Input: 
fn = async () => { 
  throw "Error";
}
inputs = []
t = 1000
Output: {"rejected":"Error","time":0}
Explanation:
The function immediately throws an error.

풀이

/**
 * @param {Function} fn
 * @param {number} t
 * @return {Function}
 */
var timeLimit = function(fn, t) {
    return async function(...args) {
        console.log("...args", ...args)
        const originalPromise = fn(...args);
        const timerPromise = new Promise((resolve, reject) => {
            setTimeout(() => reject("Time Limit Exceeded"), t)
        })
        return Promise.race([originalPromise, timerPromise])
    }
};

댓글