語法
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
