zoukankan      html  css  js  c++  java
  • Symbol 小妙处

    input 框输入后发送异步请求,页面拿到响应进行渲染。但偶尔会遇到问题:响应内容和输入结果不一致。因为 http 无法保证响应到达的顺序。

    如何解决呢?提供一个小思路。

    myRequest.js

    import request from '@/request'
    
    function myRequest (opts) {
      if (!opts.pid) throw {message: 'pid 不能为空'}
    
      const KEY = Symbol.for(opts.pid)
      const requestId = ~~myRequest[KEY] + 1
      myRequest[KEY] = requestId
    
      return request(opts)
        .then(res => {
          return myRequest[KEY] === requestId
            ? res
            : null
        })
    }
    
    export default myRequest
    
    

    我们使用 requestId 标识请求的次数,并将其封装到 myRequest 函数对象内。处理响应时,比较这两个值,若不相等则丢掉。这保证页面渲染的数据始终是最新的

    Symbol.for(..) 在全局符号注册表中搜索,来查看是否有描述文字相同的符号已经存在,如果有的话就返回它。如果没有的话,会新建一个并将其返回。

    在上例中,Symbol 保证了键的唯一性,也减少了一次判断。

  • 相关阅读:
    十六进制内存赋值
    opcode修改
    C/C++ strtok函数
    pat1033. To Fill or Not to Fill (25)
    pat1008. Elevator (20)
    pat1089. Insert or Merge (25)
    pat1091. Acute Stroke (30)
    pat1002. A+B for Polynomials (25)
    pat1090. Highest Price in Supply Chain (25)
    pat1088. Rational Arithmetic (20)
  • 原文地址:https://www.cnblogs.com/fayin/p/11858555.html
Copyright © 2011-2022 走看看