async、await、promise

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~
*/
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 簡(jiǎn)單介紹下這幾個(gè)的關(guān)系為方便起見 用以下代碼為例簡(jiǎn)單介紹下這幾個(gè)東西的關(guān)系, async 在函數(shù)聲明前使用asyn...
    _我和你一樣閱讀 21,482評(píng)論 1 24
  • 一. Callback (回調(diào)函數(shù)) 1.定義:把函數(shù)當(dāng)作變量傳到另一個(gè)函數(shù)里,傳進(jìn)去之后執(zhí)行甚至返回等待之后的...
    hutn閱讀 1,616評(píng)論 0 2
  • 原文連接:https://blog.csdn.net/sinat_17775997/article/details...
    小豆soybean閱讀 4,363評(píng)論 0 7
  • Promise 對(duì)象 Promise 的含義 Promise 是異步編程的一種解決方案,比傳統(tǒng)的解決方案——回調(diào)函...
    neromous閱讀 8,832評(píng)論 1 56
  • 回調(diào)地獄 回調(diào)地獄嵌套多個(gè)方法調(diào)用會(huì)創(chuàng)建錯(cuò)綜復(fù)雜的代碼,會(huì)難以理解與調(diào)試。當(dāng)想要實(shí)現(xiàn)更復(fù)雜的功能時(shí),回調(diào)函數(shù)也會(huì)存...
    Inlight先森閱讀 2,895評(píng)論 0 4

友情鏈接更多精彩內(nèi)容