[Javascript] Broadcaster + Operator + Listener pattern -- 22. mapError, wrap fetch with broadcaster with cancellation

export let mapError = transform => broadcaster => listener => {
  return broadcaster((value) => {
    if (value instanceof Error) {
      listener(transform(value))
      return
    }
    listener(value)
  })
}

let getUrl = url => listener => {
  let controller = new AbortController()
  let signal = controller.signal
  fetch(url, {signal})
    .then((response) => {
        return response.json()
    })
    .then(listener)
    .catch(listener)

    return () => {
      controller.abort()
    }
}

let cancel = mapError(error => ({
  login: error.message
}))(getUrl("https://api.github.com/users/xxx"))(console.log)
// cancel()

 

posted @ 2020-11-26 03:15  Zhentiw  阅读(69)  评论(0编辑  收藏  举报