JS 代码片段

防止重复发送多个请求

只发送一次请求,以防止用户重复点击。

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)
ahctc-js初级
JSRUN前端笔记, 是针对前端工程师开放的一个笔记分享平台,是前端工程师记录重点、分享经验的一个笔记本。JSRUN前端采用的 MarkDown 语法 (极客专用语法), 这里属于IT工程师。