월하점
월하점의 개발 공부 일지
월하점
전체 방문자
오늘
어제
  • 분류 전체보기 (96)
    • Back-end (3)
    • PROJECT (1)
    • CS (15)
      • Operating System (0)
      • Network (4)
      • Data Structure (7)
      • Algorithm (0)
      • Database (4)
    • Problem Solving (52)
    • Programming Languages (1)
      • Javascript (0)
      • Python (1)
      • JAVA (0)
    • Codestates BEB 4기 (7)
    • Blockchain (12)
    • Linux (2)
    • Git (1)
    • 잡다한 (2)

공지사항

인기 글

태그

  • django
  • 네트워크
  • Python
  • javascript
  • 프로그래머스
  • 자료구조
  • node.js
  • 알고리즘
  • SWEA
  • CS
  • baekjoon

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
월하점

월하점의 개발 공부 일지

  • HOME
  • GUEST
  • WRITE
Back-end

[Node.js] TestDome Solution - First Promise

2022. 9. 14. 23:13

문제

A company uses a Node.js application that checks several data sources for requested information. Since each request to a data source is performance heavy, the application should try to check the next source only if the request failed at the current data source. That functionality was extracted into the firstSuccessfulPromise function.

The firstSuccessfulPromise function accepts an array of Promises as a promiseArray parameter. The function should return a Promise which should resolve to the first successful result from the promiseArray.

If no Promise from the promiseArray returns successfully, the function should return undefined.

For example, if the following code is executed:

firstSuccessfulPromise([new Promise((resolve, reject) => reject()),
              new Promise((resolve, reject) => resolve("Success!"))])
  .then(result => console.log(result));

It should print "Success!".

 

async function firstSuccessfulPromise(promiseArray) {
  // Write your code here
}

let promise = firstSuccessfulPromise([new Promise((resolve, reject) => reject()), 
              new Promise((resolve, reject) => resolve("Success!"))]);
promise.then(result => console.log(result));

module.exports.firstSuccessfulPromise = firstSuccessfulPromise;

 

 

 

답안

async function firstSuccessfulPromise(promiseArray) {
  // Write your code here
  const invert = p => new Promise((res,rej) => p.then(rej,res))
  const firstOf = ps => invert(Promise.all(ps.map(invert)))
  return await firstOf(promiseArray).catch(err => undefined)
}

let promise = firstSuccessfulPromise([new Promise((resolve, reject) => reject()), 
              new Promise((resolve, reject) => resolve("Success!"))]);
promise.then(result => console.log(result));

module.exports.firstSuccessfulPromise = firstSuccessfulPromise;

Tests: 4 pass / 0 fail

  • Example case: Correct answer
  • The first Promise in promisesArray returns successfully: Correct answer
  • The first successful Promise in promisesArray is not the first Promise in the array: Correct answer
  • The function returns undefined only if no Promise is successful: Correct answer

 

풀이

아이디어: Promise.all() 의 특성을 활용해 invert 시키기

Invert the polarity of the promises, and then you can use Promise.all, because it rejects on the first rejected promise, which after inversion corresponds to the first fulfilled promise
  • Promise.all() : 주어진 프로미스 중 하나라도 거부하면, 다른 프로미스의 이행 여부에 상관없이 첫 번째 거부 이유를 사용해 거부합니다.

 즉, Promise.all() 이 reject 된 프로미스가 있다면 첫번째 reject를 반환하는 특성을 이용하는 것이다!

프로미스의 resolve 와 reject 위치를 invert 시켜준다면, 거부된 프로미스가 아닌 첫번째로 성공한 프로미스 반환도 가능해진다!!!

 

 

참고한 스택오버플로우는 여기이다.

 

혼자선 도저히 생각을 못해냈는데 정말 깔끔하고 clever 그 자체다…. 기본기의 중요성이 바로 이런 거구나.

저작자표시 비영리 변경금지 (새창열림)

'Back-end' 카테고리의 다른 글

Nodejs와 mysql 모듈 연동 에러 해결 | Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client  (0) 2022.04.16
Django 웹프로그래밍 bash 명령어  (0) 2020.09.26
    'Back-end' 카테고리의 다른 글
    • Nodejs와 mysql 모듈 연동 에러 해결 | Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
    • Django 웹프로그래밍 bash 명령어
    월하점
    월하점
    개발 공부를 기록합니다. 웹을 위주로 공부하며 컴퓨터과학 이론도 함께 정리할 계획입니다.

    티스토리툴바