es6的async,await
Async/Await應該是目前最簡單的異步方案了,ES7 中新增了 async/await 兩個關鍵詞。async 能夠聲明一個異步函數,此函數須要返回一個 Promise 對象。await 能夠等待一個 Promise 對象 resolve,並拿到結果。 一個栗子:
//同步
/*console.log(1);
console.log(2);
console.log(3);
console.log(4);
//異步 ajax 文件讀取io操做
console.log(1);
console.log(2);
setTimeout(function(){
console.log(3000);
},3000);
console.log(3);
console.log(4);
//先打印1 2 3 4,隔三秒後打印3000;
//async函數返回的是resolve狀態的Promise對象
async function fn(){
return "abc";
}
let result=fn();
console.log(result);//打印:Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: "abc"}。*/
//Promise 對象
/*let p = new Promise(function(resolve,reject){
resolve("abc");
});
p.then(function(data){
console.log(data);//打印abc。
});
//async函數裏面的返回值傳遞給then方法
async function fn(){
return "123";
}
let p1 = fn();
p1.then(function(data){
console.log(data);//打印123.
});*/
//async函數用來處理異步
function yi1(){
return new Promise(function(resolve,reject){
setTimeout(function(){
console.log("yi1_3000");
resolve("yi1_3000");
},3000);
})
}
function yi2(){
return new Promise(function(resolve,reject){
setTimeout(function(){
console.log("yi2_2000");
resolve("yi2_2000");
},2000);
})
}
//await只能出如今異步函數裏面,
async function yibu(){
console.log("start");
let r1 = await yi1();
console.log(r1);
let r2 = await yi2();
console.log(r2);
return "end";
}
let p3 = yibu();
p3.then(r=>{
console.log("end");
});
//先打印start,三秒後打印兩次yi1_3000,而後隔兩秒打印兩次yi2_2000和end;
值得注意的是,await必須在async函數的上下文中的。
await看起來就像是同步代碼,因此能夠理所固然的寫在for循環裏,沒必要擔憂以往須要閉包才能解決的問題。
既然.then(..)不用寫了,那麼.catch(..)也不用寫,能夠直接用標準的try catch語法捕捉錯誤。