Flutter-Daily-Interview icon indicating copy to clipboard operation
Flutter-Daily-Interview copied to clipboard

第005期 await for的使用方式

Open wyufeng02 opened this issue 5 years ago • 2 comments

wyufeng02 avatar Aug 03 '19 16:08 wyufeng02

代码如下

String data;
getData() async {
  data = await http.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});     //延迟执行后赋值给data
}
  • await关键字必须在async函数内部使用
  • 调用async函数必须使用await关键字
  • 返回默认是一个future对象
//定义了返回结果值为String类型
Future<String> getDatas(String category) async {
    var request = await _httpClient.getUrl(Uri.parse(url));  
    var response = await request.close();
    return await response.transform(utf8.decoder).join();
}

run() async{
    int data = await getDatas('keji');    //因为类型不匹配,IDE会报错
}

Furture的作用是为了链式调用

//案例3
 funA(){
  ...set an important variable...    //设置变量
}

funB(){
  ...use the important variable...   //使用变量
}
main(){
  new Future.then(funA()).then(funB());   // 明确表现出了后者依赖前者设置的变量值
 
  new Future.then(funA()).then((_) {new Future(funB())});    //还可以这样用

  //链式调用,捕获异常
  new Future.then(funA(),onError: (e) { handleError(e); }).then(funB(),onError: (e) { handleError(e); })  
}

Natoto avatar Aug 06 '19 09:08 Natoto

await for 常用于Stream

onlyYU avatar Jun 11 '23 07:06 onlyYU