문제
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 usePromise.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 그 자체다…. 기본기의 중요성이 바로 이런 거구나.