zoukankan      html  css  js  c++  java
  • ES6

    Promise 实例化

    const P = new Promise(function(resolve, reject){
    
      setTimeout(function(){
    
        //let data = '数据读取成功';
    
        //resolve(data);//将成功函数赋予resolve属性
    
        let  err = " 数据读取失败"
    
        reject(err);//将失败函数赋予resolve属性
      },1000)
    }
    //测试的情况下,用那个,显示哪个,目前代码是激活失败状态

    调用promise对象 的then方法, 从而实现坚挺成功失败

    P.then(function(value){
    
      console.log(value)
    
    },function(error){
    
      console.log(error)
      console.error(error) })

    promise 封装ajax

    const url = 'https://api.apiopen.top/getJoke'
        const ajax = new Promise((resolve,reject) => {
            //1. 创建对象
            const xhr = new XMLHttpRequest();
            //2. 初始化
            xhr.open("GET",url);
            //3. 发送
            xhr.send();
            //4. 绑定时间,处理相应结果
            xhr.onreadystatechange = function(){
                //判断结果状态
                if(xhr.readyState === 4){
                    //判断响应状态吗200-290
                    if(xhr.status >=200 && xhr.status<300){
                        //成功回调
                        resolve(xhr.response);
                    }
                    else{
                        //失败回调
                        reject(xhr.status)
                    }
                }
            }
        });
        //指定回调
        ajax.then(function(res){
            console.log(res)
        },function(error){
            console.error(error);
        })

    //ES6 写法
    /*
    ajax.then(res=>{
    console.log(res)
    },error=>{
    console.error(error);
    })
       */
  • 相关阅读:
    POJ2960 S-Nim
    HDU1850 Being a Good Boy in Spring Festival
    描述性统计-1
    基础-1
    .Net程序调试
    家装设计
    ACDSee技巧
    Timeline Maker 用法小结
    Windows 7 操作系统核心文件
    艺术字的操作
  • 原文地址:https://www.cnblogs.com/ningxin/p/14466305.html
Copyright © 2011-2022 走看看