async/await 和promise的理解


語法

async 函數返回一個 Promise 對象
 1.
async function  f() {
    return 'hello world'
};
f().then( (v) => console.log(v)) // hello world

2.
async function e(){
    throw new Error('error');
}
e().then(v => console.log(v))
.catch( e => console.log(e));
async 函數返回的 Promise 對象,必須等到內部所有的 await 命令的 Promise 對象執行完,才會發生狀態改變
const delay = timeout => new Promise(resolve=> {
      setTimeout(()=>{
            console.log(timeout);
            resolve();      
      }, timeout)
});
async function f(){
    console.log('begin');
    await delay(1000);
    await delay(500);
    await delay(200);
    console.log('end');  
    return 'done';
}

f().then(v => console.log(v)); // 等待1700ms后才輸出 'done'

正常情況下,await 命令后面跟着的是 Promise ,如果不是的話,也會被轉換成一個 立即 resolve 的 Promise
async function  f() {
    return await 1
};
f().then( (v) => console.log(v)) // 1
Async 函數的錯誤處理
/ 正確的寫法
let a;
async function correct() {
    try {
        await Promise.reject('error')
    } catch (error) {
        console.log(error);
    }
    a = await 1;
    return a;
}

correct().then(v => console.log(a)); // 1

文獻參考:
1.https://juejin.im/post/596e142d5188254b532ce2da
2.https://juejin.im/post/5b9db6925188255c3b7d78cb


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM