关于javascript:请求缓存并调用回调

32次阅读

共计 888 个字符,预计需要花费 3 分钟才能阅读完成。

/**
 * 申请缓存,并调用回调
 */
function cacheRequest(fn) {
  let hasReq = 1; // 未申请 -1 申请中 -2 申请胜利 -3
  let result = null;
  const cals = [];
  return function (...args) {const options = args[0];
    const callback = args[1];
    function myCallback(res) {
      hasReq = 3;
      result = res;
      for (let i = 0; i < cals.length; i++) {cals[i](res);
      }
    }
    console.log('hasReq', hasReq)
    if (hasReq === 1) {
      hasReq = 2
      cals.push(callback);
      fn(options, myCallback);
    } else if (hasReq === 3) {callback(result);
    } else {cals.push(callback);
    }
  }
}

// 应用 promise
function cacheRequest2(fn) {
  let p = null;
  return function (...args) {const [options, callback] = args;
    if (!p) {p = new Promise((resolve) => {fn(options, (res) => {resolve(res);
        })
      })
    }
    p.then(callback);
  }
}

// 应用示例
const fn = (options, callback) => {
  // 发动申请等,而后调用 callback
  setTimeout(() => {callback(1);
  });
}
const cachedReq = cacheRequest2(fn)

cachedReq({}, (data) => {console.log('data', data);
})
cachedReq({}, (data) => {console.log('data', data);
})
setTimeout(() => {cachedReq({}, (data) => {console.log('data', data);
  })
});

正文完
 0