Skip to content

Commit

Permalink
feat(utils): 新增 pMap
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jan 8, 2021
1 parent 362ccd3 commit 449332d
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export * from './parseUrlQueryString'
export * from './pascalCase'
export * from './pickStrict'
export * from './placeKitten'
export * from './pMap'
export * from './readFile'
export * from './RichUrl'
export * from './run'
Expand Down
12 changes: 12 additions & 0 deletions src/utils/pMap.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { expectType } from '../dev'
import { pMap } from './pMap'

describe('pMap', () => {
test('表现正常', async () => {
const res = await pMap([1, 2], item =>
item === 1 ? item : Promise.resolve(item),
)
expectType<typeof res, number[]>()
expect(res).toEqual([1, 2])
})
})
20 changes: 20 additions & 0 deletions src/utils/pMap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* `Promise.all(data.map(callback))` 的简写。
*
* @param list 列表数据
* @param callback 回调
* @example
* ```typescript
* const res = await pMap(
* [1, 2],
* i => Promise.resolve(i),
* )
* // => [1, 2]
* ```
*/
export function pMap<T, R>(
list: T[],
callback: (item: T, index: number, list: T[]) => R | PromiseLike<R>,
): Promise<R[]> {
return Promise.all(list.map(callback))
}

0 comments on commit 449332d

Please sign in to comment.