async摇展、await吻氧、promise三者是es6新增的關(guān)鍵字,async-await 是建立在 promise機(jī)制之上的咏连,并不能取代其地位盯孙。
async: 作為一個(gè)關(guān)鍵字放在函數(shù)前面,用于表示函數(shù)是一個(gè)異步函數(shù)祟滴,因?yàn)閍sync就是異步的異步振惰,異步函數(shù)也就是意味著這個(gè)函數(shù)的執(zhí)行不會(huì)阻塞后面代碼的執(zhí)行。
async基本語法:
async function func(){
............
}
func();
async表示函數(shù)異步垄懂,定義的函數(shù)會(huì)返回一個(gè)promise對(duì)象骑晶,可以使用then方法添加回調(diào)函數(shù)。
async function demo(){
return "hello async!";
}
console.log(demo());
demo().then((data) => {
console.log(data);
});
console.log('first exec');
/*
若 async 定義的函數(shù)有返回值埠偿,return 'hello async!';相當(dāng)于Promise.resolve('hello async!'),沒有聲明式的 return則相當(dāng)于執(zhí)行了Promise.resolve();
Promise { 'hello async!' }
first exec
hello async!
*/
如果async內(nèi)部發(fā)生錯(cuò)誤,使用 throw 拋出榜晦,catch捕獲
async function demo(flag){
if(flag){
return 'hello world!!';
}else{
throw "happend err!";
}
}
demo(0).then((val)=>{
console.log(val);
}).catch((val)=>{
console.log(val);
});
console.log('first exec');
/*
first exec
happend err!
*/
await: 是等待的意思冠蒋,那么它在等待什么呢,它后面跟著什么呢乾胶?其實(shí)它后面可以放任何表達(dá)式抖剿,不過我們更多放的是一個(gè)promise對(duì)象的表達(dá)式朽寞。注意await關(guān)鍵字,只能放在async函數(shù)里面,不能單獨(dú)使用斩郎。
async function Func() {
await Math.random();
}
Func();
/*
SyntaxError: await is only valid in async function
*/
await 后面可以跟任何的JS 表達(dá)式脑融。雖然說 await 可以等很多類型的東西,但是它最主要的意圖是用來等待 Promise 對(duì)象的狀態(tài)被 resolved缩宜。如果await的是 promise對(duì)象會(huì)造成異步函數(shù)停止執(zhí)行并且等待 promise 的解決,如果等的是正常的表達(dá)式則立即執(zhí)行肘迎。
function demo(){
return new Promise((resolve, reject) => {
resolve('hello promise!');
});
}
(async function exec(){
let res = await demo();
console.log(res); //hello promise!
})();
Promise : 對(duì)象用于表示一個(gè)異步操作的最終狀態(tài)(完成或失敗)锻煌,以及該異步操作的結(jié)果值妓布。它有三種狀態(tài):pending,resolved宋梧,rejected
1匣沼、Promise從pending狀態(tài)改為resolved或rejected狀態(tài)只會(huì)有一次,一旦變成resolve或rejected之后捂龄,這個(gè)Promise的狀態(tài)就再也不會(huì)改變了释涛。
2、通過resolve(retValue)傳入的retValue可以是任何值倦沧,null也可以唇撬,它會(huì)傳遞給后面的then方法里的function去使用。通過rejected(err)傳入的err理論上也是沒有限制類型的刀脏,但我們一般都會(huì)傳入一個(gè)Error局荚,比如reject(new Error(“Error”))
await 若等待的是 promise 就會(huì)停止下來。業(yè)務(wù)是這樣的愈污,我有三個(gè)異步請(qǐng)求需要發(fā)送耀态,相互沒有關(guān)聯(lián),只是需要當(dāng)請(qǐng)求都結(jié)束后將界面的 loading 清除掉即可.
function sleep(second) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('request done! '+ second + Math.random());
}, second);
})
}
async function bugDemo() {
console.log(await sleep(2000));
console.log(await sleep(3000));
console.log(await sleep(1000));
console.log('clear the loading~');
}
bugDemo();
/*
request done! 20000.9130830570273656
request done! 30000.5404841472398161
request done! 10000.26831404663460434
clear the loading~
*/