• 用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("网络异常"));
            }
        })
    }

     

  • 相关阅读:
    Robberies
    Big Event in HDU
    UVA 562 Dividing coins
    Little Rooks
    Bone Collector
    Piggy-Bank
    0-1背包问题之——饭卡
    Monkey and Banana
    The Triangle
    Burning Midnight Oil
  • 原文地址:https://www.cnblogs.com/yanghai/p/14092233.html
Copyright © 2020-2023  润新知