mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-23 14:15:13 +00:00
fix(utils): support chaining functions with promise (#8038)
This commit is contained in:
parent
6828ba9184
commit
7961e539da
@ -13,24 +13,28 @@ export const chainFn = function chainFn (base, fn) {
|
|||||||
if (typeof fn !== 'function') {
|
if (typeof fn !== 'function') {
|
||||||
return base
|
return base
|
||||||
}
|
}
|
||||||
return function (...args) {
|
|
||||||
if (typeof base !== 'function') {
|
if (typeof base !== 'function') {
|
||||||
return fn.apply(this, args)
|
return fn
|
||||||
}
|
}
|
||||||
let baseResult = base.apply(this, args)
|
|
||||||
// Allow function to mutate the first argument instead of returning the result
|
return function (arg0, ...args) {
|
||||||
if (baseResult === undefined) {
|
const next = (previous = arg0) => {
|
||||||
[baseResult] = args
|
const fnResult = fn.call(this, previous, ...args)
|
||||||
|
|
||||||
|
if (fnResult && typeof fnResult.then === 'function') {
|
||||||
|
return fnResult.then(res => res || previous)
|
||||||
}
|
}
|
||||||
const fnResult = fn.call(
|
|
||||||
this,
|
return fnResult || previous
|
||||||
baseResult,
|
|
||||||
...Array.prototype.slice.call(args, 1)
|
|
||||||
)
|
|
||||||
// Return mutated argument if no result was returned
|
|
||||||
if (fnResult === undefined) {
|
|
||||||
return baseResult
|
|
||||||
}
|
}
|
||||||
return fnResult
|
|
||||||
|
const baseResult = base.call(this, arg0, ...args)
|
||||||
|
|
||||||
|
if (baseResult && typeof baseResult.then === 'function') {
|
||||||
|
return baseResult.then(res => next(res))
|
||||||
|
}
|
||||||
|
|
||||||
|
return next(baseResult)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -103,4 +103,15 @@ describe('util: task', () => {
|
|||||||
const chainedFn = chainFn(firstFn, secondFn)
|
const chainedFn = chainFn(firstFn, secondFn)
|
||||||
expect(chainedFn({}, 10)).toEqual({ bar: 12 })
|
expect(chainedFn({}, 10)).toEqual({ bar: 12 })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('chainFn (promise)', async () => {
|
||||||
|
const firstFn = () => Promise.resolve({ foo: 1 })
|
||||||
|
const secondFn = function (obj) {
|
||||||
|
obj.foo++
|
||||||
|
return Promise.resolve()
|
||||||
|
}
|
||||||
|
|
||||||
|
const chainedFn = chainFn(firstFn, secondFn)
|
||||||
|
expect(await chainedFn()).toEqual({ foo: 2 })
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
Loading…
Reference in New Issue
Block a user