async函数
2018-09-26 本文已影响0人
牛耀
async函数(源自ES2017)
概念: 真正意义上去解决异步回调的问题,同步流程表达异步操作
本质: Generator的语法糖
语法:
async function foo(){
await 异步操作;
await 异步操作;
}
特点:
1、不需要像Generator去调用next方法,遇到await等待,当前的异步操作完成就往下执行
2、返回的总是Promise对象,可以用then方法进行下一步操作
3、async取代Generator函数的星号*,await取代Generator的yield
4、语意上更为明确,使用简单,经临床验证,暂时没有任何副作用
//async基本使用
async function foo(){
return new Promise(resolve => {
// setTimeout(function(){
// resolve();
// }, 2000);
setTimeout(resolve, 2000);
})
}
async function test(){
console.log('开始执行', new Date().toTimeString());
await foo();
console.log('执行完毕', new Date().toTimeString());
}
// test();
// async里await的返回值
function test2(){
return 'xxx';
}
async function asyncPrint(){
// let result = await test2();
let result = await Promise.resolve('promise');
console.log(result);
result = await Promise.reject('失败了~');
console.log(result)
}
// asyncPrint();
// 获取新闻内容
async function getNews(url){
return new Promise((resolve, reject) => {
$.ajax({
url,
type: 'GET',
dataType: 'json'
})
.done(data => resolve(data))
// .fail(error => reject());
.fail(error => resolve(false));
});
}
async function sendXml(){
let result = await getNews('http://localhost:3000/newsasdf?id=7');
console.log(result);
if(!result){
alert('暂时没有新闻推送~~');
return;
}
result = await getNews('http://localhost:3000' + result.commentsUrl);
console.log(result);
console.log('错误了~~');
}
sendXml();