企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## Future ### catchError or onError catchError ``` Future.delayed(Duration(seconds: 2),(){ //return "hi world!"; throw AssertionError("Error"); }).then((data){ //执行成功会走到这里 print("success"); }).catchError((e){ //执行失败会走到这里 print(e); }); ``` onError ``` Future.delayed(Duration(seconds: 2), () { //return "hi world!"; throw AssertionError("Error"); }).then((data) { print("success"); }, onError: (e) { print(e); }); ``` ### wait 等待多个返回结果 ``` Future.wait([ // 2秒后返回结果 Future.delayed(Duration(seconds: 2), () { return "hello"; }), // 4秒后返回结果 Future.delayed(Duration(seconds: 4), () { return " world"; }) ]).then((results){ print(results[0]+results[1]); }).catchError((e){ print(e); }); ``` ### whenComplete 不管是否成功,都会执行 whenComplete ``` Future.delayed(Duration(seconds: 2),(){ //return "hi world!"; throw AssertionError("Error"); }).then((data){ //执行成功会走到这里 print(data); }).catchError((e){ //执行失败会走到这里 print(e); }).whenComplete((){ //无论成功或失败都会走到这里 }); ``` ## Stream 可以接收多个异步操作的结果(成功或失败)。 Stream 常用于会多次读取数据的异步任务场景,如网络内容下载、文件读写等. ``` Stream.fromFutures([ // 1秒后返回结果 Future.delayed(Duration(seconds: 1), () { return "hello 1"; }), // 抛出一个异常 Future.delayed(Duration(seconds: 2),(){ throw AssertionError("Error"); }), // 3秒后返回结果 Future.delayed(Duration(seconds: 3), () { return "hello 3"; }) ]).listen((data){ print(data); }, onError: (e){ print(e.message); },onDone: (){ }); ```