Skip to content

Commit

Permalink
feat: add promiseSeries
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Mar 30, 2019
1 parent 859c8b4 commit 3843fba
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/Wechat.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { EventBus } from './EventBus'
import { promiseSeries } from './promiseSeries'

declare const wx: any

Expand Down Expand Up @@ -191,11 +192,12 @@ export class Wechat {
...params,
}
// 必须顺序调用分享接口,否则会失败!
return this.invoke('updateAppMessageShareData', params)
.then(() => this.invoke('updateTimelineShareData', params))
.then(() => {
this.prevShareParams = params
})
return promiseSeries([
() => this.invoke('updateAppMessageShareData', params),
() => this.invoke('updateTimelineShareData', params),
]).then(() => {
this.prevShareParams = params
})
}

chooseImage(params?: WechatChooseImageParams): Promise<string[]> {
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export * from './parseCSSValue'
export * from './pick'
export * from './placeKitten'
export * from './preventEventDefault'
export * from './promiseSeries'
export * from './randomString'
export * from './range'
export * from './reduce'
Expand Down
14 changes: 14 additions & 0 deletions src/promiseSeries.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export function promiseSeries<
// eslint-disable-next-line space-before-function-paren
T extends (...args: any) => Promise<any>,
R extends (T extends (...args: any) => Promise<infer X> ? X : any),
>(tasks: T[]) {
return tasks.reduce<Promise<R[]>>(
(promise, task) => promise.then(
resultList => task().then(
result => resultList.concat(result),
),
),
Promise.resolve([]),
)
}
13 changes: 13 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1633,3 +1633,16 @@ describe('wait', () => {
expect(time2 - time1 >= 1000).toBeTruthy()
})
})

describe('promiseSeries', () => {
test('ok', async () => {
const a = (): Promise<number> => Promise.resolve(1)
const b = (): Promise<string> => Promise.resolve('2')
const c = (): Promise<boolean> => Promise.resolve(false)
const d = (): Promise<boolean> => Promise.reject('error')
const pList = [a, b, c]
expect(vtils.isPromise(vtils.promiseSeries(pList))).toBeTruthy()
expect(await vtils.promiseSeries(pList)).toEqual([1, '2', false])
expect(vtils.promiseSeries(pList.concat(d))).rejects.toBe('error')
})
})

0 comments on commit 3843fba

Please sign in to comment.