当前位置:首页 > 自己实现一个简单的axios

自己实现一个简单的axios

发布于 2019-10-25 阅读 1624 次 Javascript

一次面试被问到的问题,当时没想起来,回来自己写了这个东西,轻拍。

  1. function Axios(){
  2. }
  3. Axios.prototype.then = function (cal){
  4. this.cal = cal
  5. }
  6. Axios.prototype.send = function(url, method, data){
  7. //创建xml对象 调用open 调用send(用settimeout模拟)
  8. var _this = this;
  9. setTimeout(function(){
  10. console.log(_this.cal)
  11. _this.cal.call(this, 'data'+url)
  12. },1000)
  13. return this;
  14. }
  15. var axios = new Axios();
  16. axios.send('url', 'method', 'data').then(function(data){
  17. console.log(data);
  18. });

大概意思就是:

  1. send和then方法放到原型上面
  2. then接受一个回调函数,这个回调函数有一个参数data
  3. 然后调用send里面写异步的请求,请求回来的回调函数(成功失败回调)调用then方法(this.then(function(data){处理data}))这样就把返回的数据传给then方法了。