消除异步传染
Hello World

消除异步传染

snowlove
1年前发布 /正在检测是否收录...

function getUser() {
  return fetch('https://my-json-server.typicode.com/typicode/demo/profile')
}

function m1() {
  // other works
  return getUser();
}

function m2() {
  // other works
  return m1();
}

function m3() {
  // other works
  return m2();
}

function main(){
 const res = m3()
 console.log("main",res) // main Promise { <pending> }
}

main()

// 要求:在不改动以上方法的情况下 如何避免使用async await方法 将所有方法都传染为同步方法 且控制台输出请求结果

// 一种方法
/**
 * function main(){
    m3().then(res=>{console.log("main",res)})  // {"name": "typicode"}
  }
 */

 // 另一种方法
function run(func){
  const _originWindowFetch = globalThis.fetch
  const cache = new Map()
  // 1.第一次请求直接报错
  // 2.当接口请求成功后,缓存结果,在下次同意请求时将缓存结果返回
  globalThis.fetch = (...args) => {
      const url = args[0]
      const fetchStatus = {
        requestId: url,
        status: 'pending', // pending; fulfilled; rejected
        data: null,
        err: null,
      }
      let cacheFetch = cache.get(url)
      // 此处判断是否有缓存
      if(cacheFetch){
        if(cacheFetch.status === 'fulfilled'){
          // 移除
          cache.delete(url)
          return cacheFetch.data
        }
        if(cacheFetch.status === 'rejected'){
          // 移除
          cache.delete(url)
          throw cacheFetch.err
        }
      }
      cacheFetch = cache.set(url,fetchStatus).get(url)
      // 首次请求获得缓存返回值
      const promise = _originWindowFetch(args).then((resp) => resp.json())
       .then(res=>{
        cacheFetch.status = 'fulfilled'
        cacheFetch.data = res
       },err=>{
        cacheFetch.status = 'rejected'
        cacheFetch.err = err
       })
       .catch((err) => {
        cacheFetch.status = 'rejected'
        cacheFetch.err = err
      })
       throw promise
  }
  try {
    func()
  } catch (error) {
    if(error instanceof Promise){
        const runFun = ()=>{
          func()
        }
        // 重新执行 此处已经获取到请求结果
        error.then(runFun,runFun).catch(runFun)
    }
  }
}

run(main)
© 版权声明
THE END
喜欢就支持一下吧
点赞 0 分享 收藏
评论 抢沙发
取消
SSL