微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

promise

axios基本用法

axios.defaults.baseURL='https://d18c4217.cn'
async function aaa(){
   const a = await axios.get('/fictionSelect.php');
   return a
}
aaa().then(a=>{
   console.log(a)
})

promise基本用法

<script type="text/javascript">
    const i=new Promise(function(resolve,reject){
        setTimeout(()=>{
            const flag=false;
            if(!flag){
                resolve('成功')
            }else{
                reject('失败')
            }
        },1000)
    })
    i.then(data=>{
        console.log(data)//成功
    })
</script>

promise创建ajax

function promise(url){
    var p=new Promise(function(resolve,reject){
        var xhr=new XMLHttpRequest()
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    resolve(xhr.responseText)
                }else{
                    reject('请求出错')
                }
            }
        }
        xhr.open('post',url)
        xhr.send(null)
    })
    return p
}
promise('http://v.juhe.cn/joke/randJoke.php?key=886be12054b5d84dbab2f01eab08ac8b')
.then(res=>{
        const data=JSON.parse(res)
    })

Ajax函数封装

// Ajax封装
function ajax(url,callback){
    var xhr=new XMLHttpRequest()
    xhr.open('get',url)
    xhr.send()
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if(xhr.status==200){
                callback(xhr.responseText)
            }else{
                return console.log('请求失败')
            }
        }
    }
}
//回调函数,ajax异步有一个过程,
//consloe的时候可能ajax过程还没好
//这时consloe了就会undefine

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐