ES6 作爲多年來 JavaScript 的重大版本變革,受到 JavaScript 開發者們的普遍歡迎,也正是從 ES6 (ES2015) 開始,JavaScript 版本發佈變爲年更,即每年發佈一個新版本,以年號標識版本
隨着async/await正式納入ES7標準,據說是異步編程終級解決方案的 async/await。
async 是“異步”的意思,而 await 是等待的意思,await 用於等待一個異步任務執行完成的結果。
- async/await 是一種編寫異步代碼的新方法(以前是採用回調和 promise)。
- async/await 是建立在 promise 的基礎上。
- async/await 像 promise 一樣,也是非阻塞的。
- async/await 讓異步代碼看起來、表現起來更像同步代碼。
一、Async
1、async
async修飾的函數就是異步函數,該函數的返回值是promise對象。
async function f1(){
return "hello f1";
}
var t = f1();
console.log(t);// promise對象。
f1().then(function(str){
console.log("str:"+str); //str:hello f1
});
2、async和promise的對比
async function f1(){
return "hello f1";
}
function f2(){
return new Promise((resolve, reject) => {
resolve('hello f2');
})
}
f1().then(function(str){
console.log("str:"+str);
});
f2().then(function(str){
console.log("str:"+str);
});
從以上代碼可以看到,執行結果一樣。Asnyc修飾的函數的返回值會作爲resolve對應函數的參數。
二、await
首先,await只能寫在async修飾的函數裏。Await是等待的意思,await修飾的代碼會等待。在函數裏,碰到await修飾的代碼時,await朝後的代碼都會等待。
async function f1() {
console.log("f1開始");
const data = await "hello await"; //await後面的代碼停止。
console.log("--------終於等到其它代碼執行完畢----------");
console.log(data);
return data;
}
f1().then(function(str){
console.log("str:"+str);
});
console.log("外部的");
執行結果:
三、面試題:
async,await,promise,setTimeout的執行順序
setTimeout(function(){
console.log(1);
},1000);
setTimeout(function(){
console.log(2);
},0);
// Promise.resolve(console.log(3)).then(()=>{
// console.log(4);
// });
new Promise(function(resolve,reject){
console.log(3);
resolve();
}).then(()=>{
console.log(4);
});
async function async1(){
console.log(5);
await async2();
console.log(6);
}
async function async2(){
console.log(7);
}
async1();
console.log(8);