只发送一次请求,以防止用户重复点击。
function firstPromise(promiseFunction) {
// Cache request instance
let p = null
return function (...args) {
// 如果请求的实例已经存在,说明请求正在进行中,
// 直接返回该实例,而不触发新的请求。
return p
? p
// 否则就发送该请求,并在Promise结束时将p设置为null,然后可以重新发送下一个请求
: (p = promiseFunction.apply(this, args).finally(() => (p = null)))
}
}
let count = 1
let promiseFunction = () =>
new Promise((rs) =>
setTimeout(() => {
rs(count++)
}, 1000)
)
let firstFn = firstPromise(promiseFunction)
firstFn().then(console.log) // 1
firstFn().then(console.log) // 1
firstFn().then(console.log) // 1
setTimeout(() => {
firstFn().then(console.log) // 2
firstFn().then(console.log) // 2
firstFn().then(console.log) // 2
}, 3000)