Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Like Array.some and on the contrast of Promise.race, there is a Promise.some
function some_sync(...ps) {
return (async () => {
let errors = []
while (true) {
try {
return await ps[errors.length]
} catch (error) {
errors.push(error)
if (errors.length === ps.length) {
throw errors
}
}
}
})()
}
function some_async(...ps) {
return new Promise(function(resolve, reject) {
let errors = [], resolved = false
function got_resolve(data) {
!resolved && resolve(data)
}
function got_reject(error, i) {
errors[i] = error
if (errors.filter(e => e).length===ps.length) {
reject(errors)
}
}
ps.forEach((p, i) => p.then(got_resolve).catch(function(error) {
got_resolve(error, i)
}))
})
}
function some(...pss) {
return some_async(...pss.map(ps => some_sync(...ps)))
}
// test
function get(a) {
return new Promise((resolve,reject)=>{
// console.log(a);
setTimeout(function(){
if (a>0) {
console.log(a)
resolve(a)
} else {
console.log(a)
reject(a)
}
}, Math.abs(a)*1000)
});
}
some([get(-1), get(-2), get(-1)], [get(3)]).then(n => console.log(n)).catch(e => console.log('err'))
@xialvjun

This comment has been minimized.

Copy link
Owner Author

@xialvjun xialvjun commented Oct 25, 2016

API is: some([p1, p2, p3], [p4, p5], [p6])
p1/p4/p6 同时进行,p1进行完之后进行p2,以此类推.....当然,因为 Promise是在刚创建时就已经开始执行了的,所以。。。。。没用

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment