首页 > 其他 > 详细

ES6 - Promise

时间:2021-03-01 22:55:01      阅读:42      评论:0      收藏:0      [点我收藏+]

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);
})
   */

 

ES6 - Promise

原文:https://www.cnblogs.com/ningxin/p/14466305.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!