Created
October 25, 2016 15:01
-
-
Save xialvjun/f4312057b2830a040a8e7c271be49457 to your computer and use it in GitHub Desktop.
Like Array.some and on the contrast of Promise.race, there is a Promise.some
This file contains hidden or 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
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')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
API is:
some([p1, p2, p3], [p4, p5], [p6])
p1/p4/p6 同时进行,p1进行完之后进行p2,以此类推.....当然,因为 Promise是在刚创建时就已经开始执行了的,所以。。。。。没用