zoukankan      html  css  js  c++  java
  • [Javascript] Broadcaster + Operator + Listener pattern -- 25. Save Network Requests by Using a Cache

    Caches exist to make things faster (at the expense of taking up more memory and possibly outdated results). Our live search is a great use case for implementing a cache, so let's set up a mapBroadcasterCache operator which can map a string to the result of a broadcaster.

    export let mapBroadcasterCache = createBroadcaster => broadcaster => listener => {
      let cache = new Map()
      let cancel
    
      return broadcaster(value => {
        // abort previous 
        if (cancel) {
          cancel()
          return;
        } 
    
        if (cache.has(value)) {
          listener(cache.get(value))
          return
        }
        let newBroadcaster = createBroadcaster(value)
        cancel = newBroadcaster((newValue) => {
          // Add to cache only if newValue isn't an error
          if (!(newValue instanceof Error)) {
            cache.set(value, newValue)
            }
          console.log(cache)
          listener(newValue)
        })
      })
    }
    export let ignoreError = broadcaster => listener => {
      return broadcaster((value) => {
        if (value instanceof Error) {
          return
        }
        listener(value)
      })
    }

    Using:

      let inputToBooks = pipe(
        filter(name => name.length > 3),
        waitFor(150),
        pipe(
          map(name => `https://openlibrary.org/search.json?q=${name}`),
          mapBroadcasterCache(getUrl),
          ignoreError,
          map(json => json.docs)
        ))(inputValue)
  • 相关阅读:
    数据库连接池
    数据库操作
    cookie/session
    楼梯问题
    Response/Request
    Web
    Exception
    jQuery效果与事件方法
    jQuery基础知识点
    布局的几种形式
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14108976.html
Copyright © 2011-2022 走看看