zoukankan      html  css  js  c++  java
  • 用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("网络异常"));
            }
        })
    }

     

  • 相关阅读:
    Git标签使用技巧
    Git入门基本概述
    过滤器+缓存在.NET5WebApi项目中的简单使用
    在.NET5中 使用JWT鉴权授权
    Git常用开发命令
    时间戳的实际使用
    两个日期字段相减,进行计算
    MQ的理论理解
    第一周学习C语言的总结!
    问题(the question)
  • 原文地址:https://www.cnblogs.com/yanghai/p/14092233.html
Copyright © 2011-2022 走看看