31. 实现async helper - `race()`
分享给更多人
容易 -通过 / -执行
这个题目是30. 实现async helper - parallel()
的后续。
请实现一个async function helper - race()
。 race()
有点类似Promise.race()。 parallel()
会等待所有的function执行结束,race()
会在任何一个function结束或者产生error的时候调用最终的callback。
本题目中的所有异步函数是如下interface。
type Callback = (error: Error, data: any) => void
type AsyncFunc = (
callback: Callback,
data: any
) => void
你的race()
需要 接受 AsyncFunc 数组,并且返回一个新的函数。这个函数会在任何一个function调用结束或者发生error的时候被调用。
假设我们有如下3个async function。
const async1 = (callback) => {
setTimeout(() => callback(undefined, 1), 300)
}
const async2 = (callback) => {
setTimeout(() => callback(undefined, 2), 100)
}
const async3 = (callback) => {
setTimeout(() => callback(undefined, 3), 200)
}
你的race()
需要使得如下逻辑成立。
const first = race(
[
async1,
async2,
async3
]
)
first((error, data) => {
console.log(data)
// 2, 因为2是第一个成功执行的结果
}, 1)