Skip to content

Instantly share code, notes, and snippets.

@sshplendid
Last active September 21, 2020 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sshplendid/986f68c495361ec8b4d7ef185b30f403 to your computer and use it in GitHub Desktop.
Save sshplendid/986f68c495361ec8b4d7ef185b30f403 to your computer and use it in GitHub Desktop.
Promise.race 상황에서 나머지 프로미스를 처리하려면?
// 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