• 用promise 封装 ajax(来自牛客)


    请使用Promise封装Ajax操作
    原始的Ajax操作如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    var onSuccess = function(result){}; //成功的回调
    var onFail = function(error){}; //失败的回调
    var req = new XMLHttpRequest();
    req.open("POST""www.baidu.com"true);
    req.onload = function(){
      if(req.readyState === 4 && req.status === 200){
        onSuccess(req.response);
      else {
        onFail(req.statusText);
      }
    }
    req.onerror = function(){
      onFail(Error("网络异常"));
    }
     
    解:------------------------------------------------------------------------------------------------------------------------------------------
    const ajax = url => {
        return new Promise((resolve, reject) => {
            let req = new XMLHttpRequest();
            req.open("POST", url, true);
            req.onload = () => {
              if(req.readyState === 4 && req.status === 200){
                resolve(req.response);
              else {
                reject(req.statusText);
              }
            }
            req.onerror = () => {
              reject(Error("网络异常"));
            }
        })
    }

     

  • 相关阅读:
    魔兽世界祭拜长者
    Mono嵌入C++
    kxb-shell文件操作-kxb
    GAN初步理解
    Pytorch 常用函数方法的理解
    转载:StyleGAN & StyleGAN2 论文解读
    RepVGG
    多目标跟踪,REID, JDE跟踪器解析
    卷积和反卷积详细说明
    FairMOT解析
  • 原文地址:https://www.cnblogs.com/yanghai/p/14092233.html
Copyright © 2020-2023  润新知