dart异步编程

by Mohammed Salman

穆罕默德·萨尔曼(Mohammed Salman)

如何通过期货将一些异步编程引入Dart (How to bring a little asynchronous programming to Dart with futures)

Asynchronous programming is a form of parallel programming that allows a unit of work to run separately from the primary application thread. When the work is complete, it notifies the main thread (as well as whether the work was completed or failed). There are numerous benefits to using it, such as improved application performance and enhanced responsiveness.

异步编程是并行编程的一种形式,它允许一个工作单元与主应用程序线程分开运行。 工作完成后,它会通知主线程(以及工作是完成还是失败)。 使用它有很多好处,例如提高了应用程序性能和增强了响应能力。

Originally posted on my blog.

最初发布在我的博客上。

TL;DR.

TL; DR 。

问题 (Problem)

Dart code runs in a single thread of execution, so if it’s blocked the entire program freezes.

Dart代码在单个执行线程中运行,因此如果被阻止,则整个程序将冻结。

Example:

例:

//..
var data = fetchDataFromSomeApi(); // Takes time while fetching data
doStuffWithData(data); // Manipulate the data
doOtherStuff(); // Do other stuff unrelated to the data
//..

Since fetchDataFromSomeApi() blocks, the remaining code runs only after fetchDataFromSomeApi() returns with the data, however long that takes.

由于fetchDataFromSomeApi()阻塞,因此其余代码仅在fetchDataFromSomeApi()返回数据后才运行, 但要花很长时间

This code runs line by line causing the code to halt and doOtherStuff() to run after the data fetching operation is finished (which is probably not what you want).

这段代码逐行运行,导致代码终止,并且doOtherStuff()在数据获取操作完成后运行(这可能不是您想要的)。

解 (Solution)

Asynchronous operations let your program complete other work while waiting for other operation to finish.

异步操作使您的程序可以在等待其他操作完成的同时完成其他工作。

Same example as above, but with an asynchronous approach:

与上述示例相同,但采用异步方法:

fetchDataFromSomeApi().then((data) {  print('Fetched data');  doStuffWithData(data);});
print('Working on other stuff...');doOtherStuff();
// Output://   Working on other stuff...//   Fetched data

fetchDataFromSomeApi is non-blocking, meaning it lets other code run while fetching data. Thats why the top level print statement runs before the print statement in the callback function.

fetchDataFromSomeApi是非阻塞的,这意味着它允许其他代码在获取数据时运行。 这就是为什么顶级print的前语句运行print在回调函数声明。

期货 (Futures)

A future represents a computation that doesn’t complete immediately. Where a normal function returns the result, an asynchronous function returns a future, which will eventually contain the result. The future will tell you when the result is ready.

未来表示无法立即完成的计算。 普通函数返回结果的地方,异步函数返回未来的结果,最终将包含结果。 将来会告诉您结果准备就绪的时间。

Future objects (futures) represent the results of asynchronous operations — processing or I/O to be completed later.

Future对象( 期货 )表示异步操作的结果-处理或稍后要完成的I / O。

We can create a future simply like this:

我们可以像这样简单地创造未来:

Future future = Future();

let’s define a function called f:

让我们定义一个名为f的函数:

String f() => 'work is done!';

and pass it to the future:

并将其传递给未来:

Future<String> future = Future(f);

Notice that the future takes the same type of the function f return type String.

请注意,future的功能与f返回类型String类型相同。

For the purposes of this tutorial we passed a function that just returns a string. This creates a future containing the result of calling f asynchronously with Timer.run.

就本教程而言,我们传递了一个仅返回字符串的函数。 这将创建一个Timer.run其中包含与Timer.run异步调用f的结果。

If the result of executing f throws, the returned future is completed with the error.

如果执行f的结果抛出,则返回的future将完成并显示错误。

If the returned value is itself a Future, completion of the created future will wait until the returned future completes, and will then complete with the same result.

如果返回的值本身是Future ,则创建的future的完成将等待,直到返回的future完成为止,然后将以相同的结果完成。

If a non-future value is returned, the returned future is completed with that value.

如果返回了非未来值,则返回的Future将使用该值完成。

然后 (then)

let’s call then on the future and pass a function that takes the output of the asynchronous operation as an argument

让我们把then在未来,通过一个函数,它的异步操作的输出作为参数

future.then((String val) => print(val)); // work is done

we can simplify it by passing the print function only because it takes a string

我们可以通过传递print函数来简化它,因为它只需要一个字符串

future.then(print); // work is done

错误处理 (Error handling)

To catch errors, use try-catch expressions in async functions (or use catchError()).

要捕获错误,请在异步函数中使用try-catch表达式(或使用catchError() )。

catchError (catchError)

let’s imagine that our future throws an error at some point:

让我们想象一下我们的未来会在某个时候抛出错误:

Future future = Future(() => throw Error());

If we call then on the future without handling the error, it will throw the error and stop the execution of our program:

如果我们在将来调用then而不处理错误,它将抛出错误并停止执行程序:

future.then(print); // Error: Error: Instance of 'Error'

Let’s define a function that takes an error and handles it:

让我们定义一个接受错误并处理它的函数:

void handleError(err) { print(‘$err was handled’);}

then append catchError() to the future and pass handleError:

然后将catchError()追加到将来并传递handleError

future.then(print).catchError(handleError); // Error: Error: Instance of 'Error' was handled

This way the error is handled and the program keeps executing.

这样,错误得以处理,程序继续执行。

异步,等待 (Async, Await)

To suspend execution until a future completes, use await in an async function (or use then()).

要暂停执行直到将来完成,请在异步函数中使用await (或使用then() )。

To use the await keyword, it has to be inside an async function like this:

要使用await关键字,它必须在如下所示的async函数中:

main() async { Future future = Future(() => ‘work is done’); String res = await future; print(res); // work is done}

Notice that the main function is marked with the async keyword.

注意, main函数用async关键字标记。

Any function marked with async is called asynchronously.

带有async标记的任何函数都被异步调用。

When we call a future with the await keyword, the function execution is halted until the future returns a value or throws an error.

当我们使用await关键字调用await ,函数的执行将停止,直到future返回一个值或引发错误。

We can handle future errors using a trycatch block:

我们可以使用trycatch块来处理将来的错误:

main() async { Future future = Future(() => throw Error()); try {   print(await future);  } catch (e) {   print(‘$e was handled’); // Instance of 'Error' was handled }}

结论 (Conclusion)

  • Dart code runs in a single “thread” of execution.Dart代码在单个“执行”线程中运行。
  • Code that blocks the thread of execution can make your program freeze.阻塞执行线程的代码会使您的程序冻结。
  • Future objects (futures) represent the results of asynchronous operations — processing or I/O to be completed later.

    Future对象( 期货 )表示异步操作的结果-处理或稍后要完成的I / O。

  • To suspend execution until a future completes, use await in an async function (or use then()).

    要暂停执行直到将来完成,请在异步函数中使用await (或使用then() )。

  • To catch errors, use try-catch expressions in async functions (or use catchError()).

    要捕获错误,请在异步函数中使用try-catch表达式(或使用catchError() )。

If you feel that I have missed something here please let me know, or if you have any question at all you can reach me on twitter.

如果您觉得我在这里错过了什么,请告诉我,或者如果您有任何疑问,可以通过twitter与我联系。

Subscribe to my newsletter!

订阅我的时事通讯 !

其他有用的资源 (Other useful resources)

Asynchronous Programming: Futures

异步编程:期货

翻译自: https://www.freecodecamp.org/news/dart-asynchronous-programming-futures-5b20c62a91c0/

dart异步编程

dart异步编程_如何通过期货将一些异步编程引入Dart相关推荐

  1. python execute异步执行_封装了一个对mysql进行异步IO的小工具

    作者(微信公众号):猿人学Python SanicDB 是为 Python的异步 Web 框架 Sanic 方便操作MySQL而开发的工具,是对 aiomysql.Pool 的轻量级封装.Sanic ...

  2. 硬件趣学python编程_没有人比我更懂编程,慧编程'吮指编辑器',简单快乐学python...

    咳咳! 大家好,我是偶尔写文章的康康老师. 今天跟大家介绍的是慧编程家的,睡在Scratch上铺的兄弟--慧编程Python编辑器. 这是一款集才华和颜值为一体的'吮指'编辑器! 忘记肯德基,你的手指 ...

  3. java io 网络编程_[笔面] Java IO和网络编程相关面试

    1.网络编程时的同步.异步.阻塞.非阻塞? 同步:函数调用在没得到结果之前,没有调用结果,不返回任何结果. 异步:函数调用在没得到结果之前,没有调用结果,返回状态信息. 阻塞:函数调用在没得到结果之前 ...

  4. 交换最大数与最小数java编程_善知教育笔记之JavaSE_Java编程基础

    1 Java编程基础 1.1 变量 1.1.1 变量 变量是什么?为什么为用变量? 变量就是系统为程序分配的一块内存单元,用来存储各种类型的数据.根据所存储的数据类型的不同,有各种不同类型的变量.变量 ...

  5. java 多线程 异步日志_精彩技巧(1)-- 异步打印日志的一点事

    一.前言 最近刚刚结束转岗以来的第一次双11压测,收获颇多,难言言表, 本文就先谈谈异步日志吧,在高并发高流量响应延迟要求比较小的系统中同步打日志已经满足不了需求了,同步打日志会阻塞调用打日志的线程, ...

  6. python socket编程_最基础的Python的socket编程入门教程

    本文介绍使用Python进行Socket网络编程,假设读者已经具备了基本的网络编程知识和Python的基本语法知识,本文中的代码如果没有说明则都是运行在Python 3.4下. Python的sock ...

  7. java和python混合编程_浅谈C++与Java混合编程

    在学习编程的过程中, 我觉得不止要获得课本的知识, 更多的是通过学习技术知识提高解决问题的能力, 这样我们才能走在最前方, 更 多 Java 学习,请登陆疯狂 java 官网. 现实的情况是, 真实的 ...

  8. kotlin函数式编程_我最喜欢的Kotlin函数式编程示例

    kotlin函数式编程 by Marcin Moskala 通过Marcin Moskala One of the great things about Kotlin is that it suppo ...

  9. python模块化编程_什么是模块,Python模块化编程(入门必读)

    Python 提供了强大的模块支持,主要体现在,不仅 Python 标准库中包含了大量的模块(称为标准模块),还有大量的第三方模块,开发者自己也可以开发自定义模块.通过这些强大的模块可以极大地提高开发 ...

最新文章

  1. Linux 启动详解之init
  2. PHP递归复制文件夹的类
  3. .net知识和学习方法系列(十四)TraceListener的应用
  4. 工作总结22:拦截器
  5. 响应文件是不是标书_标书的编制
  6. 四、Mysql安装多实例
  7. 光猫gpon和epon的区别
  8. 轻量级日志收集转发 | fluent-bit指令详解(一)
  9. 转未来10年35项最值得你期待的技术
  10. anisotropy texture filtering
  11. PB控件属性之Tab
  12. 43套高质量PPT模板—创意风格主题
  13. 数字化转型,你也可以品
  14. 从微信小程序到QQ小程序:云开发CloudBase的一云多端实践
  15. 上传身份证照片js_身份证正反面上传插件
  16. 7z文件格式及其源码的分析
  17. java随机点名器_随机点名器(Java实现、读取txt文件)
  18. arcgis上下标问题
  19. IT运维的学习流程与方向
  20. AutoJS实现淘金币任务,双十二任务

热门文章

  1. 2021-2025年中国脱水泵行业市场供需与战略研究报告
  2. 自动化部署工具瓦力(walle)的安装
  3. Scrapy-Splash爬取淘宝排行榜(二)
  4. 封神台-尤里的复仇II 回归sql-注入绕过防护getshell
  5. 免费的几个CDN加速
  6. C++之string的compare用法
  7. 用c语言编写rfid读卡系统,USB免驱RFID读写器编程解析之一:智能卡篇
  8. 怎样播放swf文件 swf格式怎么转换成mp3格式
  9. RGB颜色空间转LAB
  10. 新手引导的界面部分操作区域的处理(一)