Last active
September 21, 2020 05:45
-
-
Save sshplendid/986f68c495361ec8b4d7ef185b30f403 to your computer and use it in GitHub Desktop.
Promise.race 상황에서 나머지 프로미스를 처리하려면?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Promise 생성기 | |
function getPromise(msg, timeout) { | |
return new Promise((res, rej) => { | |
setTimeout(() => { | |
res(msg) | |
}, timeout || 1000) | |
}) | |
} | |
// race처럼 첫 번째를 처리하고 나머지도 처리기를 붙여놓음 | |
function raceButAll(promises, other) { | |
const size = promises.length | |
let count = 0 | |
return new Promise((res,rej) => { | |
promises.forEach(promise => { | |
promise | |
.then((v) => { | |
count += 1; | |
if(count === 1) { | |
res(v) | |
} else { | |
other(v) | |
} | |
}) | |
}) | |
}) | |
} | |
raceButAll( | |
[1,2,3,4].map(n => getPromise(n, n*1000)), | |
v => console.log('나머지 프로미스', v), | |
).then( v => console.log('첫번째 프로미스', v)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment