Promise的理解

/*

    1. promise讲解
    1. 原生js中实现promise
    1. jquery中实现promise
    1. node启静态文件服务
      */

Promise 是什么

一种异步解决方案,相当于一种规范。

如果遇到多个接口调用的时候,这时候就尽管使用promise就可以了

以前处理异步的方式

        $.ajax({
            // ...., 
            success:function(){  //成功之后的状态 id
                // 获取到id;
                
                // name
                $.ajax({
                    // id
                     success:function(){
                        //  name
                        $.ajax({
                            // id
                            success:function(){
                                //  name

                            }

                        })
                     }

                })
            } 
        });

Promise 详细介绍

    Promise 解决js中多个异步回调优化/维护...的问题。
    异步
    同步

    原生js提供了promise对象
    let pro = new Promise();

    es6中promise对象是一个构造函数,用来生成promise实例。

    // axios

js jQuery中实现

//原生js封装公共的promise对象
const getJSON = function(url,type,data){
    const promise = new Promise(function(resolve,reject){
        const handler = function() {
            if(this.readyState !==4){
                return;
            };
            if(this.status === 200){  //成功的状态
                resolve(this.response);
            }else{  //失败
                reject(new Error(this.statusText));
            }
          };
         const client = new XMLHttpRequest();//创建对象
         client.open(type,url);//建立连接
         client.onreadystatechange = handler;
         client.responseType = 'json';//数据格式
         if(type =='get'){
             client.send();  //发送get请求
         }else{
             client.setRequestHeader("Content-type","application/json");//头信息
             client.send(JSON.stringify(data));
         }
    });
    return promise;    
}

//使用封装的promise:
        // post请求
        getJSON("http://localhost:3000/add","post",{name:name,msg:msg})
        .then(function(res){ //成功
            console.log(res);
            for(let i=0;i<res.length;i++){
                $(".messageList").append(`<li class="list-group-item">${res[i].name}
                <span>说:</span> ${res[i].msg}
            </li>`);
            }
        },function(error){ //失败
            console.log(error);
            
        });

        //get请求
        getJSON("http://localhost:3000/add","get")
        .then(function(res){ //成功
            console.log(res);
        },function(error){ //失败
            console.log(error);
        })

        // //链式写法  串行
        getJSON("http://localhost:3000/add","get")
        .then(function(res){ //成功  第一个请求完成了,  id

            console.log(res);

        },function(err){
            console.log(err);
            
        })
        .then(function(){  //再进行另一个请求 
            // name 订单里的名称
        },function(err){
            console.log(err);
            
        })
        .then(function(){  //再进行另一个请求 
            // name 订单里的名称
        })
        .then(function(){   
            // name 订单里的名称
        },function(err){
            console.log(err);
            
        })
// jq
$(function(){
       //提交
    $(".container .submit").click(()=>{
        let _name = $(".name").val();
        let _msg = $(".message").val();
        if(_name == '' || _msg==''){
            alert("请输入内容");
        }else{
            $(".name,.message").val("");
            //列表展示
            // 第一种写法
            $.ajax({
                url:'http://localhost:3000/add',
                type:'post',
                data:{name:_name,msg:_msg},
                dataType:'json'
            })
            .then(function(res){

            })
            .then(function(res){

            })
            .then(function(res){

            })
            .catch(function(err){

            })


            // 第二种写法
            $.ajax({
                url:'http://localhost:3000/add',
                type:'post',
                data:{name:_name,msg:_msg},
                dataType:'json'
            })
            .done(function(res){
                console.log(res);
                for(let i=0;i<res.length;i++){
                    $(".messageList").append(`<li class="list-group-item">${res[i].name}
                    <span>说:</span> ${res[i].msg}
                </li>`);
                } 
            })
            .fail(function(err){
                console.log(err);
                
            })

            // 两者的区别:done不支持链式写法,不会延续任务的调用。 then则相反。
            // 只需要调用一次  done 
            // 链式写法 then
        }
    }); 
})

//jq串行写法
$(function(){
    //提交
    $(".queryThen").click(()=>queryThen());
    let queryThen = ()=>{
        //发送的第一个请求  id
        $.ajax({
            url:'http://localhost:3000/add',
            type:'get',
            dataType:'json'
        })
        .then(function(res){  //成功
            // id
            // 发送的第二个请求
            return $.ajax({
                url:'http://localhost:3000/add2',
                type:'post',
                data:{name:_name,msg:_msg},
                dataType:'json'
            })
        })
        .then(function(res){

        },function(err){

        })
    }
});


//jq 并行  两个请求同时发
$(function(){
    //提交
    $(".queryWhen").click(()=>queryWhen());
    let queryWhen = ()=>{
        //发送的第一个请求  id
        $.when($.ajax({url:'http://localhost:3000/add',type:'get',dataType:'json'}),
                $.ajax({url:'http://localhost:3000/add',type:'post',dataType:'json',{name:_name,msg:_msg}))

        .then(function(data1,data2){  //成功
            console.log(data1);
            console.log(data2);
        })
        
    }
});

 

Promise.then()

// //链式写法  串行
        getJSON("http://localhost:3000/add","get")
        .then(function(res){ //成功  第一个请求完成了,  id

            console.log(res);

        },function(err){
            console.log(err);
            
        })
        .then(function(){  //再进行另一个请求 
            // name 订单里的名称
        },function(err){
            console.log(err);
            
        })
        .then(function(){  //再进行另一个请求 
            // name 订单里的名称
        })
        .then(function(){   
            // name 订单里的名称
        },function(err){
            console.log(err);
            
        })

Promise.catch()

	$.ajax({
        url:'http://localhost:3000/add',
        type:'post',
        data:{name:_name,msg:_msg},
        dataType:'json'
    })
    .then(function(res){

    })
    .then(function(res){

    })
    .then(function(res){

    })
    .catch(function(err){

    })

Promise.all()

 //原生js并行的实现
$(function(){
    //提交
    $(".queryWhen").click(()=>queryWhen());
    let queryWhen = ()=>{
         //并行 两个请求同时发  
        let getPromsie1 = new Promise(function(resolve,reject){
            getJSON("http://localhost:3000/add","get")
            .then(function(res){ //成功
                console.log(res);
               
            },function(error){ //失败
                console.log(error);
                
            });
        });
        let getPromsie2 = new Promise(function(resolve,reject){
            getJSON("http://localhost:3000/add","post",{name:'aa'})
            .then(function(res){ //成功
                console.log(res);
               
            },function(error){ //失败
                console.log(error);
                
            });
        });
        promise.all([getPromsie1,getPromsie2])
        .then(([data1,date2])=>{  //成功
            console.log(data1);
            console.log(date2);
            
        },function(err){ //失败
            console.log(err);
            
        })
    }
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ེ夜雨微澜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值