zoukankan      html  css  js  c++  java
  • [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()
  • 相关阅读:
    2-5
    2-4 及 1、2两章 学习心得 和问题
    2-3
    4-8
    4-6
    4-5
    4-4
    4-3
    4-2
    4-1
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14040209.html
Copyright © 2011-2022 走看看