es6 ajax async,es6-async的用法

作用:使得异步操作更加方便

基本操作:async会返回一个Promise对象,有了这个对象可以使用then,catch进行调用

async的Generatro的一个语法糖

async function fn(params) {

let aa = await 'hello async';//想用await 必须在async函数中

let data = await aa.split('');

return data;

}

//如果async有多个await,那么then函数会等待所有的await指令,运行完的结果,才去执行

fn().then(v=>{console.log(v)}).catch(e=>console.log(e))

//["h", "e", "l", "l", "o", " ", "a", "s", "y", "n", "c"]

//----------------------------------------------------------------------------------------------------

async function f2(){

throw new Error('出错了');

}

f2().then(v=>console.log(v)).catch(e=>console.log(e));//Error: 出错了

//----------------------------------------------------------------------------------------------------

await 出错之后不会执行后面的函数 想要执行后面的函数 要这样做

async function f2(){

try{

await Promise.reject('出错了')

}catch(Error){

}

return await Promise.resolve('hello')

}

f2().then(v=>console.log(v)).catch(e=>console.log(e));//hello

需求:获取一个天气

const getJSON = function(url){

return new Promise((resolved,rejected)=>{

const xhr = new XMLHttpRequest();

xhr.open('Get',url);

xhr.onreadystatechange = handler;

xhr.responseType = 'json';

xhr.setRequestHeader('Accept','application/json');

//发送

xhr.send();

function handler(){

console.log(this);

if(this.readyState === 4){

if(this.status == 200){

resolved(this.response);

}else{

rejected(new Error(this.statusText))

}

}

}

})

}

async function getNowWeather(url){

// 发送ajax 获取天气信息

let res = await getJSON(url);

// let arr = await res.weather 根据上一个结果做另外一个请求,返回两个结果

console.log(res);

return res.data;

}

getNowWeather('https://www.qweather.com/v2/current/condition/s/shanghai-101020100.html?lang=&_=1623856500')

.then(now=>{

console.log(now)

})

总结Generator Promise async

解决回调地域的问题

使得异步操作显得更加方便

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值