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 变成串行