1. 程式人生 > >async, await運用

async, await運用

{} 函數聲明 並行 his const promise code 中斷 async

1.async 函數聲明及調用方式:

 1 // async 函數聲明,調用
 2 const a1 = async() => {
 3     console.log("this is an async function1")
 4 };
 5 
 6 async function a2() {
 7     console.log("this is an async function2")
 8 }
 9 
10 a1();
11 a2();
12 (async ()=>{console.log("this is an async function3")})()

2.async 函數返回值:async 函數會返回一個Promise對象,所以處理返回值的方式和Promise一毛一樣

1 // async 函數返回值
2 const b1 = async (arg) => {
3     return arg
4 }
5 var res = b1(‘hello‘);
6 res.then(resolve=>{console.log(resolve)});

3.直接獲取async 函數返回值: await

1 // 直接獲取 async函數返回值: await需要與 async 函數搭配
2 var ret = async (x) => {
3     return x
4 }
5 var solve = async () => {
6     var
some_ret = await ret(‘hello,world‘); 7 console.log(some_ret); 8 } 9 solve();
1 // 也可以直接獲取 Promise 返回值
2 var solvePromise = async() => {
3     var some_ret = await new Promise(resolve=>{
4         resolve(‘hello, world‘)
5     })
6     console.log(some_ret);
7 }
8 solvePromise();

await的作用是 中斷當前函數體中語句的執行, 等待await 後 Promise 執行完畢;

4.async 函數串行執行

1 // async 函數串行執行方式
2 const a = async() => {
3     const b = await (async () => {})()
4     const c = await (async () => {})()
5 }
6 a();

5.async 函數並行執行

1 // async 函數並行執行方式
2 const a = async () => {
3     const b = (async () => {})()
4     const c = (async () => {})()
5     const b1 = await b;
6     const c1 = await c;
7 }
8 a();
9 // b,c 會分別先執行, 在b1 和 c1 變成串行

async, await運用