实现一个支持串行执行promise的函数
function seqPromise (arr, initValue) {
return arr.reduce((lastPromise, currentPromise) => {
return lastPromise.then(currentPromise)
}, Promise.resolve(initValue))
}
var p1 = res => new Promise((resolve, reject) => {
console.log('p1:', res)
resolve('p1' + res)
})
var p2 = res => new Promise((resolve, reject) => {
console.log('p2', res)
resolve('p2' + res)
})
seqPromise([p1, p2], 'init')
// p1: init
// p2 p1init
// Promise {<resolved>: "p2p1init"}
实现一个pipe
需求:参数为f1,f2,f3,arg,调用结果为 f3(f2(f1(arg)))
function pipeFunc (arr, arg) {
return arr.reduce((lastValue, currentFunc) => {
return currentFunc(lastValue)
}, arg)
}
var f1 = res => {
return 'f1' + res
}
var f2 = res => {
return 'f2' + res
}
pipeFunc([f1, f2], 'init') // "f2f1init"
自己实现一个reduce
Array.prototype.reduce1 = function (handle, initValue) {
var arr = this
var index = initValue ? 0 : 1
var result = initValue ? initValue : arr[0]
arr.slice(index).forEach((item, idx) => {
result = handle(result, item, idx + index, arr)
})
return result
}
var arr = ['a', 'b', 'c']
arr.reduce1((last, current, index, all) => {
console.log(last, current, index, all)
return last + current
})
// a b 1 (3) ["a", "b", "c"]
// ab c 2 (3) ["a", "b", "c"]
// "abc"
网友评论