异步

Dart中返回Futurestream对象的函数,即为异步函数
asyncawait关键字支持异步编程,这让我们能够写出和同步代码很像的异步代码

Future

Future和js中的Promise很像,表示一个异步操作的最终完成以及其结果的表示。

Future的所有API的返回仍是一个Future对象,所以很方便进行链式调用

Future.then

then中接收异步结果

Future.delayed(new Duration(seconds: 2),(){
   return "hi world!";
}).then((data){
   print(data);
});

Future.catchError

如果发生异步错误 可以再catchError中捕获错误

Future.delayed(new Duration(seconds: 2),(){
   //return "hi world!";
   throw AssertionError("Error");  
}).then((data){
   //执行成功会走到这里  
   print("success");
}).catchError((e){
   //执行失败会走到这里  
   print(e);
});

不只是catchError回调才能捕获错误,then还有可选参数onError可以使用其捕获异常

Future.delayed(new Duration(seconds: 2), () {
    //return "hi world!";
    throw AssertionError("Error");
}).then((data) {
    print("success");
}, onError: (e) {
    print(e);
});

Future.whenComplete

在异步任务无论失败或者成功都要回调

Future.delayed(new Duration(seconds: 2),(){
   //return "hi world!";
   throw AssertionError("Error");
}).then((data){
   //执行成功会走到这里 
   print(data);
}).catchError((e){
   //执行失败会走到这里   
   print(e);
}).whenComplete((){
   //无论成功或失败都会走到这里
});

Future.wait

等待多个异步任务结束,

Future.wait([
  // 2秒后返回结果  
  Future.delayed(new Duration(seconds: 2), () {
    return "hello";
  }),
  // 4秒后返回结果  
  Future.delayed(new Duration(seconds: 4), () {
    return " world";
  })
]).then((results){
//都成功触发then回调
  print(results[0]+results[1]);
}).catchError((e){
//有一个失败 就触发错误回调
  print(e);
});

Async/await

用法与js中的Async/await中一样

用于消除回调地狱

虽然可以用Future来避免回调地狱 但是还是有一层回调的

task() async {
   try{
    String id = await login("alice","******");
    String userInfo = await getUserInfo(id);
    await saveUserInfo(userInfo);
    //执行接下来的操作   
   } catch(e){
    //错误处理   
    print(e);   
   }  
}
  • async表示这是一个异步函数 函数返回一个Future对象,
  • await后面是一个Future函数 表示等待该异步函数执行完成

其实无论是在JavaScript还是Dart中,async/await都只是一个语法糖,编译器或解释器最终都会将其转化为一个Promise(Future)的调用链。

Stream

Stream也是用于接收异步事件数据,和Future不同的是,它可以接收多个异步操作的结果(成功或失败.即可以多次触发成功或者失败事件来传递结果数据或错误异常,常用于多次读取数据的异步场景任务

Stream.fromFutures([
  // 1秒后返回结果
  Future.delayed(new Duration(seconds: 1), () {
    return "hello 1";
  }),
  // 抛出一个异常
  Future.delayed(new Duration(seconds: 2),(){
    throw AssertionError("Error");
  }),
  // 3秒后返回结果
  Future.delayed(new Duration(seconds: 3), () {
    return "hello 3";
  })
]).listen((data){
   print(data);
}, onError: (e){
   print(e.message);
},onDone: (){

});