async 和 await 之异步编程的学习
生活随笔
收集整理的這篇文章主要介紹了
async 和 await 之异步编程的学习
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
????? async修改一個(gè)方法,表示其為異步方法。而await表示等待一個(gè)異步任務(wù)的執(zhí)行。js方面,在es7中開(kāi)始得以支持;而.net在c#5.0開(kāi)始支持。本文章將分別簡(jiǎn)單介紹他們?cè)趈s和.net中的基本用法。
一、在js中的實(shí)現(xiàn)
js中的異步,還是基于Promise實(shí)現(xiàn)的。沒(méi)有Promise就辦法談異步了。并且await只能出現(xiàn)async修改的方法中;以及reject會(huì)觸發(fā)catch(異常)。
class AsyncTest{//simple example async run(){//按照順序等待后輸出let one = await this.output("one", 1000);console.log('output:' one);let two = await this.output("two", 3000);console.log(two);console.log('run.....');}//await and Promise.all difference async runDiff(){ let one = this.output('diff one', 2000);let two = this.output('diff two', 2000);console.log( await two await one ); //在2秒之后,兩個(gè)都輸出了,而不是各自都等待兩秒console.log('runDiff.....');}//Promise.all realize runAll(){let nowTime = new Date();console.log('b:' nowTime.toTimeString());let array = ["a", "b", "c"];let that = this;array.forEach(async function(item){console.log( await that.output(item, 2000) );//2秒后同時(shí)輸出 });let fn = async ()=>{for(let item of array){let v = await this.output(item, 2000);console.log(v ); //分步驟兩秒執(zhí)行 }}fn.call(this);}premosFn(){let nowTime = new Date();console.log('b:' nowTime.toTimeString());let array = ["a", "b", "c"];let that = this;//promise.alllet preFn = async function(){let promises = array.map(function(item){return that.output(item,2000); //同時(shí)開(kāi)啟多個(gè)定時(shí)器 });let r = await Promise.all(promises);console.log(r.join(','));}preFn();}reject(){let rejectFn = function(){return new Promise((resolve, reject)=>{setTimeout(()=>{reject();},2000);});}let asyncReject = async function(){try{await rejectFn();}catch( e) {console.log('reject.....');}}asyncReject();}output(log, time){return new Promise(resolve=>{setTimeout(()=>{var nowTime = new Date();resolve( nowTime.toTimeString() ":" log "\r\n");}, time);});} }方法說(shuō)明如下:
- output:簡(jiǎn)單的輸出方法,但返回了一Promise。
- run: 使用await來(lái)等待兩次對(duì)output的執(zhí)行
- runDiff:調(diào)用output時(shí)即創(chuàng)建promise。兩個(gè)promise會(huì)同步執(zhí)行
- runAll:多任務(wù)同步執(zhí)行和按步驟執(zhí)行的實(shí)現(xiàn)方法。也就是forEach和for方法體中使用await的區(qū)別
- premosFn: promise.all的使用。
- reject: promise的reject會(huì)觸發(fā)await的異常。
二、在c#中的實(shí)現(xiàn)
C#中異常是通過(guò)Task來(lái)實(shí)現(xiàn)的,所以標(biāo)記了async的方法,其方法體中都可以出現(xiàn)await,否則不可以。以及Task中拋出的異常,如果沒(méi)有同步等待,則不能獲取異常
public class AsyncDemo {private Task<string> Output(string val, int time){return System.Threading.Tasks.Task.Run(() =>{System.Threading.Thread.Sleep(time * 1000);return (DateTime.Now.ToLongTimeString()) ": " val "\r\n";});}public async System.Threading.Tasks.Task Run(){string oneVal = await Output("One", 2);string twoVal = await Output("Two", 2);System.Console.WriteLine("Run \r\n" oneVal " " twoVal);}public async System.Threading.Tasks.Task RunDiff(){Task<string> oneTask = Output("one", 2);Task<string> twoTask = Output("two", 2);string val = await oneTask await twoTask; System.Console.WriteLine("RunDiff \r\n" val);}public async System.Threading.Tasks.Task RunAll(){System.Console.WriteLine("b:" (DateTime.Now.ToLongTimeString()));string[] array = new string[3] { "a", "b", "c" };foreach(var item in array){string v = await Output(item, 2);System.Console.WriteLine(v);}}public async System.Threading.Tasks.Task PromiseFn(){System.Console.WriteLine("b:" (DateTime.Now.ToLongTimeString()));string[] array = new string[3] { "a", "b", "c" };List<System.Threading.Tasks.Task<string>> tasks = new List<System.Threading.Tasks.Task<string>>();foreach (var item in array){tasks.Add(Output(item, 2));}//waitAll返回值不能獲取,他返回為void,而WhenAll則返回為一個(gè)Task(這個(gè)Task就有其列表值)string[] r = await System.Threading.Tasks.Task.WhenAll(tasks.ToArray());System.Console.WriteLine(string.Join(",",r));}public async System.Threading.Tasks.Task Reject(){Func<System.Threading.Tasks.Task> func = async () =>{throw new Exception("custom...");await Output("reject", 2);};await func();} }調(diào)用代碼如下:
AsyncDemo asyncDemo = new AsyncDemo(); asyncDemo.Run().Wait(); asyncDemo.RunDiff().Wait(); asyncDemo.RunAll().Wait(); asyncDemo.PromiseFn().Wait(); try {asyncDemo.Reject().Wait(); }catch(Exception e) {System.Console.WriteLine("reject ex"); }??? 上述代碼就是Js的async和await在c#中的翻版實(shí)現(xiàn)。 其中每個(gè)異步方法的調(diào)用,都用到了Wait方法來(lái)進(jìn)行同步等待。以獲取到結(jié)果。而沒(méi)有像Js中那么難以控制。尤其注意,async方法中異常的捕獲。
三、兩者的異同點(diǎn)
- js中的async方法的調(diào)用,是沒(méi)有wait方法來(lái)等待結(jié)果的執(zhí)行的,只能通過(guò)promise來(lái)監(jiān)聽(tīng)執(zhí)行結(jié)果
- c#中的async方法,由于推薦返回Task或者Task<T>,所以可以用Wait來(lái)等待執(zhí)行結(jié)果,如果async方法返回為void,則與js類(lèi)似。 C#中的下面示例方法的調(diào)用者捕獲不了異常:
public async void Run() {string oneVal = await Output("One", 2);string twoVal = await Output("Two", 2);System.Console.WriteLine("Run" oneVal " " twoVal); } - c#中的Task可以異步方法的鏈?zhǔn)秸{(diào)用,即可將前一任務(wù)的執(zhí)行結(jié)果作為第二任務(wù)的參數(shù)傳入,當(dāng)然js的Promise也完全是可以很輕松的實(shí)現(xiàn):
更多專(zhuān)業(yè)前端知識(shí),請(qǐng)上 【猿2048】www.mk2048.com
總結(jié)
以上是生活随笔為你收集整理的async 和 await 之异步编程的学习的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: vue命令行错误处理
- 下一篇: 【留言板】可编辑输入框操作总结