Dart异步编程-future

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();
}

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


Winning lotto numbers: [23, 63, 87, 26, 2]
Tomorrow's forecast: 70F, sunny.
Baseball score: Red Sox 10, Yankees 0

注意:
该代码存在问题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 = '';
Duration oneSecond = const Duration(seconds: 1);

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: [23, 63, 87, 26, 2]
Tomorrow's forecast: 70F, sunny.
Baseball score: Red Sox 10, Yankees 0

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

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

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

async.png
  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完成之后再执行。

未完待续.....

你可能感兴趣的:(Dart异步编程-future)