30. 实现async helper - `parallel()`
分享给更多人
中等难度 -通过 / -执行
本题目是 29. 实现async helper - sequence()
的延续。
请实现async helper - parallel()
! parallel()
有点类似Promise.all()
。和29题中的 sequence()
不同,异步函数的执行没有先后顺序,在parrallel()
中是同时触发。
本题目中的所有异步函数是如下interface。
type Callback = (error: Error, data: any) => void
type AsyncFunc = (
callback: Callback,
data: any
) => void
你的parallel()
需要能 接受 AsyncFunc 数组,并且返回一个function,这个function将会在所有的异步函数完成或者error发生的时候被触发。
假设我们有如下3个异步函数。
const async1 = (callback) => {
callback(undefined, 1)
}
const async2 = (callback) => {
callback(undefined, 2)
}
const async3 = (callback) => {
callback(undefined, 3)
}
parallel()
需要使得以下成为可能。
const all = parallel(
[
async1,
async2,
async3
]
)
all((error, data) => {
console.log(data) // [1, 2, 3]
}, 1)
当Error发生的时候,只有第一个error需要被传递到最后,剩下的error和data都被忽略。