promise async await 理解筆記

在異步編程中,es6提供了promise對象的方式。
簡單的用法es6

var promise = new Promise((resolve,reject)=>{
    if(){
        resolve(res)
    }else{
        reject(res)
    }
})
promise.the((res)=>{}).catch((res)=>{})

而async 實則是返回了一個promise對象編程

async function test(){
    console.log("123");
}
var restult = test();
console.log(result);//=>>Promise{"123"};
//若是函數return 一個直接量,那麼就等於直接去調用Promise.resolve()方法
//Promise.resolve方法也就是生成一個Promise實例,而且其直接調用resolve。
//例如
Promise.resolve('test');
//等同於
new Promise((resolve,reject)=>resolve('test'));
//因此async能夠理解爲生成一個promise實例。
//那麼天然也能夠去調用.then()
test.then((res)=>{})

await則是配合async使用的。await等因而等待一個返回值,等待async的執行結果。promise

async function testAsync() {
    return Promise.resolve("hello async");
}

async function test() {
    const res = await testAsync();
    console.log(res);
}

test();

輸出結果就是'hello async'.
await必須配合async使用,可是await的對象能夠不是Promise對象,一個普通的函數也能夠使用。
若是它等到的不是一個 Promise 對象,那 await 表達式的運算結果就是它等到的東西。
若是它等到的是一個 Promise 對象,await 就忙起來了,它會阻塞後面的代碼,等着 Promise 對象 resolve,而後獲得 resolve 的值,做爲 await 表達式的運算結果。可是async函數不會形成阻塞,因此await配合async使用,則沒有影響到外部。異步

async和await的做用
能夠把promise 的then寫得簡潔,便於理解
流程就是生成一個async函數,而後函數內部去await一個promise對象得運行結果,再用這個結果去調用其它得Promise對象,如此得話then((res)=>{}).then((ress)=>{})。就能夠寫成async

var res = await foo(); 
var ress = await fob(res);
var resss = await foc(ress)

在then鏈複雜得狀況下,promise得參數傳遞很是複雜,但使用async+await得方式,就如同同步編程通常,很是清晰和流暢。異步編程

相關文章
相關標籤/搜索