Async
1.Async函数的返回值为Promise对象
2.Promise的结果由Async函数执行的返回值决定
Await
1.必须写在Async函数中
2.Await后面的表达式一般为Promise对象
3.Await返回的是Promise成功的值
4.Await的Promise 失败了的话,需要通过try…catch捕获
//先生成一个Promise。
const p = new Promise((resolve,reject)=>{
resolve('成功的值')
})
async function fn(){
//await 要放在async函数中
let result = await p ;//awiat后面跟着的是promise,并且只返回成功的值
console.log(result)
}
fn()
而当resolve改成reject的时候
当promise为失败的时候,需要用try…catch
async function fn(){
//await 要放在async函数中
try {
let result = await p ;//awiat后面跟着的是promise,并且只返回成功的值
} catch (error) {
console.warn(error)
}
}
发送AJAX请求
<script>
//发送AJAX请求,返回的结果是Promise对象
function sendAJAX(url){
return new Promise((resolve,reject)=>{
//创建对象
const x = new XMLHttpRequest()
//初始化
x.open('GET',url)
//发送
x.send()
//事件绑定
x.onreadystatechange = function(){
if(x.readyState===4){
if(x.status>=200&&x.status<300){
//成功
resolve(x.response)
}else{
reject(x.status)
}
}
}
})
}
async function main(){
//发送AJAX请求
let result = await sendAJAX('https://api.vvhan.com/api/saorao?tel=1365655656')
console.log(result)
}
main()
</script>