Dart异步编程包含两部分:Future和Stream

该篇文章中介绍Future

异步编程:Futures

  Dart是一个单线程编程语言。如果任何代码阻塞线程执行都会导致程序卡死。异步编程防止出现阻塞操作。Dart使用Future对象表示异步操作。

介绍

  如下代码可能导致程序卡死

  

// Synchronous code
printDailyNewsDigest() {
String news = gatherNewsReports(); // Can take a while.
print(news);
} main() {
printDailyNewsDigest();
printWinningLotteryNumbers();
printWeatherForecast();
printBaseballScore();
}

该程序获取每日新闻然并打印,然后打印其他一系列用户感兴趣的信息:

<gathered news goes here>
Winning lotto numbers: [, , , , ]
Tomorrow's forecast: 70F, sunny.
Baseball score: Red Sox , Yankees

该代码存在问题printDailyNewsDigest读取新闻是阻塞的,之后的代码必须等待printDailyNewsDigest结束才能继续执行。当用户想知道自己是否中彩票,明天的天气和谁赢得比赛,都必须等待printDailyNewsDigest读取结束。

为了程序及时响应,Dart的作者使用异步编程模型处理可能耗时的函数。这个函数返回一个Future

什么是Future

Future表示在将来某时获取一个值的方式。当一个返回Future的函数被调用的时候,做了两件事情:
1. 函数把自己放入队列和返回一个未完成的Future对象
2. 之后当值可用时,Future带着值变成完成状态。
为了获得Future的值,有两种方式:
1. 使用async和await
2. 使用Future的接口

Async和await

async和await关键字是Dart异步支持的一部分。他们允许你像写同步代码一样写异步代码和不需要使用Future接口。

注:在Dart2中有轻微的改动。async函数执行时,不是立即挂起,而是要执行到函数内部的第一个await。在多数情况下,我们不会注意到这一改动

下面的代码使用Async和await读取新闻

// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file. import 'dart:async'; printDailyNewsDigest() async {
String news = await gatherNewsReports();
print(news);
} main() {
printDailyNewsDigest();
printWinningLotteryNumbers();
printWeatherForecast();
printBaseballScore();
} printWinningLotteryNumbers() {
print('Winning lotto numbers: [23, 63, 87, 26, 2]');
} printWeatherForecast() {
print("Tomorrow's forecast: 70F, sunny.");
} printBaseballScore() {
print('Baseball score: Red Sox 10, Yankees 0');
} const news = '<gathered news goes here>';
Duration oneSecond = const Duration(seconds: ); final newsStream = new Stream.periodic(oneSecond, (_) => news); // Imagine that this function is more complex and slow. :)
Future gatherNewsReports() => newsStream.first; // Alternatively, you can get news from a server using features
// from either dart:io or dart:html. For example:
//
// import 'dart:html';
//
// Future gatherNewsReportsFromServer() => HttpRequest.getString(
// 'https://www.dartlang.org/f/dailyNewsDigest.txt',
// );

执行结果:

Winning lotto numbers: [, , , , ]
Tomorrow's forecast: 70F, sunny.
Baseball score: Red Sox , Yankees
<gathered news goes here>

从执行结果我们可以注意到printDailyNewsDigest是第一个调用的,但是新闻是最后才打印,即使只要一行内容。这是因为代码读取和打印内容是异步执行的。

在这个例子中间,printDailyNewsDigest调用的gatherNewsReports不是阻塞的。gatherNewsReports把自己放入队列,不会暂停代码的执行。程序打印中奖号码,天气预报和比赛分数;当gatherNewsReports完成收集新闻过后打印。gatherNewsReports需要消耗一定时间的执行完成,而不会影响功能:用户在读取新闻之前获得其他消息。

下面的图展示代码的执行流程。每一个数字对应着相应的步骤

1. 开始程序执行
2. main函数调用printDailyNewsDigest,因为它被标记为async,所有在该函数任何代码被执行之前立即返回一个Future。
3. 剩下的打印执行。因为它们是同步的。所有只有当一个打印函数执行完成过后才能执行下一个打印函数。例如:中奖号码在天气预报执行打印。
4. 函数printDailyNewsDigest函数体开始执行
5. 在到达await之后,调用gatherNewsReports,程序暂停,等待gatherNewsReports返回的Future完成。
6. 当Future完成,printDailyNewsDigest继续执行,打印新闻。
7. 当printDailyNewsDigest执行完成过后,最开始的Future返回完成,程序退出。

注:如果async函数没有明确指定返回值,返回的null值的Future

错误处理

如果在Future返回函数发生错误,你可能想捕获错误。Async函数可以用try-catch捕获错误。

printDailyNewsDigest() async {
try {
String news = await gatherNewsReports();
print(news);
} catch (e) {
// Handle error...
}
}

try-catch在同步代码和异步代码的表现是一样的:如果在try块中间发生异常,那么在catch中的代码执行

连续执行

你可以使用多个await表达式,保证一个await执行完成过后再执行下一个

// Sequential processing using async and await.
main() async {
await expensiveA();
await expensiveB();
doSomethingWith(await expensiveC());
}

expensiveB函数将等待expensiveA完成之后再执行。

Future API

在Dart1.9之前还没有添加async和await时,你必须使用Future接口。你可能在一些老的代码中间看到使用Future接口

为了使用Future接口写异步代码,你需要使用then()方法注册一个回调。当Future完成时这个回调被调用。

下面的代码使用Future接口:

// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file. import 'dart:async'; printDailyNewsDigest() {
final future = gatherNewsReports();
future.then((news) => print(news));
} main() {
printDailyNewsDigest();
printWinningLotteryNumbers();
printWeatherForecast();
printBaseballScore();
} printWinningLotteryNumbers() {
print('Winning lotto numbers: [23, 63, 87, 26, 2]');
} printWeatherForecast() {
print("Tomorrow's forecast: 70F, sunny.");
} printBaseballScore() {
print('Baseball score: Red Sox 10, Yankees 0');
} const news = '<gathered news goes here>';
Duration oneSecond = const Duration(seconds: ); final newsStream = new Stream.periodic(oneSecond, (_) => news); // Imagine that this function is more complex and slow. :)
Future gatherNewsReports() => newsStream.first; // Alternatively, you can get news from a server using features
// from either dart:io or dart:html. For example:
//
// import 'dart:html';
//
// Future gatherNewsReportsFromServer() => HttpRequest.getString(
// 'https://www.dartlang.org/f/dailyNewsDigest.txt',
// );

注意到printDailyNewsDigest被首先调用,但是新闻在最后被打印。这是因为代码读取内容是异步执行的。

程序执行流程:

1. 程序开始执行
2. main函数调用printDailyNewsDigest函数,在函数内部调用gatherNewsReports
3. gatherNewsReports收集新闻然后返回一个Future
4. printDailyNewsDigest使用then指定Future的响应函数。调用then()返回的新Future将使用then指定回调返回的值完成。
5. 剩下的打印函数同步执行,因为他们是同步的
6. 当所有新闻到达,gatherNewsReports返回的Future带着一个包含新闻的字符串完成
7. 在printDailyNewsDigest中then函数指定的回调函数执行。打印新闻
8. 程序退出

在printDailyNewsDigest函数中then可以多种不同的方式写。

1. 使用花括号。当有多个操作的时候,这种方式比较方便

printDailyNewsDigest() {
final future = gatherNewsReports();
future.then((news) {
print(news);
// Do something else...
});
}

2. 直接传print函数

printDailyNewsDigest() =>
gatherNewsReports().then(print);

错误处理

使用Future接口,你可以使用catchError捕获错误

printDailyNewsDigest() =>
gatherNewsReports()
.then((news) => print(news))
.catchError((e) => handleError(e));

如果新闻不可用,那么代码的执行流程如下:
1. gatherNewsReports的Future带一个Error完成。
2. then的Future带一个Error完成。
3. catchError的回调处理错误,catchError的Future正常结束,错误不在被传递。

当使用Future接口时,在then后连接catchError,可以认为这一对接口相应于try-catch。

像then(), catchError返回一个带回调返回值的新Future

使用then连接多个函数

当Future返回时需要顺序执行多个函数是,可以串联then调用

expensiveA()
.then((aValue) => expensiveB())
.then((bValue) => expensiveC())
.then((cValue) => doSomethingWith(cValue));

使用Future.wait等待多个Future完成

当wait的所有Future完成时,Future.wait返回一个新的Future。这个Future带了一个包含所有等待结果的列表。

Future
.wait([expensiveA(), expensiveB(), expensiveC()])
.then((List responses) => chooseBestResponse(responses))
.catchError((e) => handleError(e));

当任意一个调用以error结束时,那么Future.wait也以一个Error结束。使用catchError处理错误

参考: https://www.dartlang.org/tutorials/language/futures

    

Dart异步编程-future的更多相关文章

  1. Dart 异步编程相关概念简述

    目录 isolate: event loop: Future: async/await: 总结 参考链接 ​ 学习 Dart 的异步编程时,需要对异步编程所涉及的相关知识体系进行梳理,我们可根据以下几 ...

  2. Netty 中的异步编程 Future 和 Promise

    Netty 中大量 I/O 操作都是异步执行,本篇博文来聊聊 Netty 中的异步编程. Java Future 提供的异步模型 JDK 5 引入了 Future 模式.Future 接口是 Java ...

  3. Dart 异步编程(三):详细认识

    基本概念 普通任务按照顺序执行:异步任务将在未来的某个时间执行. 实际演示 void main() { // waitFuture 函数是一个异步函数,阻塞会发生在函数内部 waitFuture(); ...

  4. Dart 异步编程(二):async/await

    对每一个异步任务返回的 Future 对象都使用链式操作-- then ,超过三个以上时,导致"倒三角"现象,降低代码的可阅读性. getHobbies() { post('htt ...

  5. Dart 异步编程(一):初步认识

    由于 Dart 是单线程编程语言,对于进行网络请求和I/O操作,线程将发生阻塞,严重影响依赖于此任务的下一步操作. 通常,在一个阻塞任务之后还有许许多多的任务等待被执行.下一步任务需要上一步任务的结果 ...

  6. flutter中的异步机制Future

    饿补一下Flutter中Http请求的异步操作. Dart是一个单线程语言,可以理解成物理线路中的串联,当其遇到有延迟的运算(比如IO操作.延时执行)时,线程中按顺序执行的运算就会阻塞,用户就会感觉到 ...

  7. flutter中的异步机制 Future

    饿补一下Flutter中Http请求的异步操作. Dart是一个单线程语言,可以理解成物理线路中的串联,当其遇到有延迟的运算(比如IO操作.延时执行)时,线程中按顺序执行的运算就会阻塞,用户就会感觉到 ...

  8. Flutter 的异步机制Future

    Dart是一个单线程语言,可以理解成物理线路中的串联,当其遇到有延迟的运算(比如IO操作.延时执行)时,线程中按顺序执行的运算就会阻塞,用户就会感觉到卡顿,于是通常用异步处理来解决这个问题. Dart ...

  9. dart系列之:dart中的异步编程

    目录 简介 为什么要用异步编程 怎么使用 Future 异步异常处理 在同步函数中调用异步函数 总结 简介 熟悉javascript的朋友应该知道,在ES6中引入了await和async的语法,可以方 ...

随机推荐

  1. dede:list 与 dede:arclist 的区别

    1.{dede:list}是用于列表页的文章列表调用,通常是用于list_article.htm页面,这个文章列表是可以分页的. 功能说明:表示列表模板里的分页内容列表适用范围:仅列表模板 list_ ...

  2. 【转】R语言函数总结

    原博: R语言与数据挖掘:公式:数据:方法 R语言特征 对大小写敏感 通常,数字,字母,. 和 _都是允许的(在一些国家还包括重音字母).不过,一个命名必须以 . 或者字母开头,并且如果以 . 开头, ...

  3. http请求的过程及潜在的性能优化点

    web前端的看富于部署过程 开发者将开发的代码发布到远程的服务器(webserver/cdn),用户通过访问浏览器输入相应的网址,浏览器向远程服务器发送请求,动态的增量式的加载资源 web前端就是一个 ...

  4. 基于云开发开发 Web 应用(三):云开发相关数据调用

    介绍 在完成了 UI 界面的实现后,接下来可以开始进行和云开发相关的数据对接.完成数据对接后,应用基础就打好了,接下来的就是发布上线以及一些小的 feature 的加入. 配置 在进行相关的配置调用的 ...

  5. Java对象序列化输入输出

    在网上看到一篇有关于对象序列化的代码,自己仿着写了把 在Java中,entity通过implements Serializable,然后使用ObjectInputStream和ObjectOutput ...

  6. Swift Json解析与model互转

    Json的解码与编码操作,这里使用swift自带的类JSONDecoder 和 JSONEncoder 1.基础处理 如果你的 JSON 数据结构和你使用的 Model 对象结构一致的话,那么解析过程 ...

  7. 吴裕雄--天生自然C++语言学习笔记:C++ 数据封装

    所有的 C++ 程序都有以下两个基本要素: 程序语句(代码):这是程序中执行动作的部分,它们被称为函数. 程序数据:数据是程序的信息,会受到程序函数的影响. 封装是面向对象编程中的把数据和操作数据的函 ...

  8. Elasticsearch 搜索API

    章节 Elasticsearch 基本概念 Elasticsearch 安装 Elasticsearch 使用集群 Elasticsearch 健康检查 Elasticsearch 列出索引 Elas ...

  9. Codeforces Round #602 (Div. 2, based on Technocup 2020 Elimination Round 3) E. Arson In Berland Forest

    E. Arson In Berland Forest The Berland Forest can be represented as an infinite cell plane. Every ce ...

  10. P1013 数素数

    转跳点: