一: 概念: 真正意義上去解決異步回調的問題,同步流程表達異步操做javascript
本質: Generator的語法糖java
語法:jquery
async function foo(){ajax
await 異步操做;異步
await 異步操做;async
}函數
特色:url
一、不須要像Generator去調用next方法,遇到await等待,當前的異步操做完成就往下執行對象
二、返回的老是Promise對象,能夠用then方法進行下一步操做blog
三、async取代Generator函數的星號*,await取代Generator的yield
四、語意上更爲明確,使用簡單,經臨牀驗證,暫時沒有任何反作用
<script type="text/javascript" src="./js/jquery-1.10.1.min.js"></script> <script type="text/javascript"> async function timeout(ms) { return new Promise(resolve => { setTimeout(resolve, ms); }) } async function asyncPrint(value, ms) { console.log('函數執行', new Date().toTimeString()); await timeout(ms); console.log('延時時間', new Date().toTimeString()); console.log(value); } console.log(asyncPrint('hello async', 2000)); // await async function awaitTest() { let result = await Promise.resolve('執行成功'); console.log(result); let result2 = await Promise.reject('執行失敗'); console.log(result2); let result3 = await Promise.resolve('還想執行一次');// 執行不了 console.log(result3); } awaitTest(); // 案例演示 async function sendXml(url) { return new Promise((resolve, reject) => { $.ajax({ url, type: 'GET', success: data => resolve(data), error: error => reject(error) }) }) } async function getNews(url) { let result = await sendXml(url); let result2 = await sendXml(url); console.log(result, result2); } getNews('http://localhost:3000/news?id=2')