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

原文地址:https://www.cnblogs.com/miaSlady/p/13132009.html