首页 > 技术文章 > promise对象

chenyudi 2020-03-01 21:38 原文

直接放大佬写的:https://es6.ruanyifeng.com/#docs/promise

这边写一下怎么用promise去封装请求

 

 

 

var urla =  'http://api.xuandan.com/DataApi/index?AppKey=3aw4643qpb&page=1&cid=';
    var de = '请求失败';
    var ajax = function(url){
      return   new Promise(function(resolve,reject){
                var xhr = new XMLHttpRequest();

                xhr.open('get',url);
                xhr.send();

                xhr.onreadystatechange = function(){
                    if(xhr.readyState == 4 && xhr.status == 200){
                        var res = JSON.parse(xhr.responseText);
                        resolve(res)

                    }else if(xhr.readyState !== 4 && xhr.status !== 200){
                        reject(de)
                    }
                }


        })
    }

    ajax(urla).then(res => {
        console.log(res);
    }).catch(error =>{
        console.log(error);
    })
 
 
 
 
 

推荐阅读