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

 

相关文章

最后的控制台返回空数组.控制台在ids.map函数完成之前运行va...
我正在尝试将rxJava与我已经知道的内容联系起来,特别是来自J...
config.jsconstconfig={base_url_api:"https://douban....
我正在阅读MDN中的javascript,并且遇到了这个谈论承诺并且不...
config.jsconstconfig={base_url_api:"https://douban....
这是我的代码main.cpp:#include<string>#include<...