- Dart:Scalable Application Development
- Davy Mitchell Sergey Akopkokhyants Ivo Balbaert
- 629字
- 2021-07-09 18:56:24
Introducing the await and async keywords
The await
and async
keywords were introduced in Dart 1.9.4 in order to simplify asynchronous operations. Consider the following call to a method that returns Future
:
obj.method().then(handlerFunction)
This is fine for the post part, but what if things get more complicated and handlerFunction
returns a future too?
obj.method().then(handlerFunction).then(handlerFunction2);
Things are starting to get complicated already—debugging is not straightforward. Ideally, we would want to deal with one part of the chain at a time and hold up the execution of statements until a desired operation is complete. This is what await
allows:
var f1 = await obj.aMethod(); var result = await f1.aMethod();
Functions and methods to be called with await
return Future
. They must also be declared as async
in the method's header, as does the function using the await
call:
class Foo{ Future<int> aMethod() async { return await aFunction(); } }
The async
and await
keywords simplify the code, particularly if in-line functions are being used, and they also make the asynchronous code much more readable.
Joining file paths
Most computer users have hit the issue with forward and backward slashes being used on paths in Unix-style (/home/davymitchell/
) and Windows operating systems (c:\users\davymitchell\
):
var contPath = path.join(Directory.current.path, "content"); var srcPath = path.join(contPath, "posts"); var imgPath = path.join(contPath, "img");
The path
package provides a cross-platform method join
to join folder and file names.
Creating an output folder
The output files will be placed in a folder named staticoutput
on the current path. The existence of this folder will be tested, and if it is not present, the folder will be created. Let's take a look at the following code snippet:
main() async { var contPath = path.join(Directory.current.path, "content"); var srcPath = path.join(contPath, "posts"); var imgPath = path.join(contPath, "img"); Blog staticBlog = new Blog(srcPath, imgPath); await staticBlog.initBlog(); print(Directory.current); // Create output directory if it does not exist. var outDir = new Directory('staticoutput'); var staticPath = path.join(Directory.current.path, 'staticoutput'); if (!await outDir.exists()) { outDir.create(); } // Write out main page. var outPath = path.join(staticPath, "index.html"); var pageContent = staticBlog.getFrontPage(); File indexPage = new File(outPath); await indexPage.writeAsString(pageContent, mode: FileMode.WRITE); // Return success exit code. exit(0); }
The outcome of the asynchronous method exists and is waited upon before the program continues.
Generating the front page
In Chapter 5, A Blog Server, there is a version of Blog Server called initBlog
from the constructor. It has been moved to a post object creation initialization call so that await
can be used. Methods and functions marked as async
cannot be called from constructors. The use of async
simplifies the _loadPostList
method, as there is much less nesting, as shown in the following code snippet:
_loadPostList() async { print("Loading from $_pathPosts"); Directory blogContent = new Directory(_pathPosts); var postsSrc = await blogContent.list(); await postsSrc.forEach((File f) { String postFilename = path.basenameWithoutExtension(f.path); int id = int.parse(postFilename); IDs.add(id); postPaths[id] = f.path; }); IDs.sort(); IDs = IDs.reversed.toList(); }
Previously, the posts were loaded and the blog was set up asynchronously.
Tip
If you are looking for some good blogs on Dart programming, a good place to start is http://www.dartosphere.org/, which is a blog aggregator or planet-style website with news and resources from various sources.
Now that the page content is available at a determinable time, it can be written out on a disk using the writeAsString
method. The FileMode.WRITE
permission will overwrite any existing file, hence is suitable for updates. Let's take a look at the following code snippet:
var outPath = path.join(staticPath, "index.html"); var pageContent = staticBlog.getFrontPage(); File indexPage = new File(outPath); indexPage.writeAsStringSync(pageContent, mode:FileMode.WRITE); exit(0);
The last line returns an exit code to the OS when the program completes, with 0
being the convention for success. This function does not wait for any pending operations, closing the program immediately.
- Hands-On Machine Learning with scikit:learn and Scientific Python Toolkits
- 算法基礎:打開程序設計之門
- 深入實踐Spring Boot
- 青少年美育趣味課堂:XMind思維導圖制作
- Learning ELK Stack
- 從Excel到Python:用Python輕松處理Excel數據(第2版)
- Linux Device Drivers Development
- Swift語言實戰精講
- INSTANT Silverlight 5 Animation
- Python+Office:輕松實現Python辦公自動化
- Arduino Electronics Blueprints
- C#網絡編程高級篇之網頁游戲輔助程序設計
- R語言:邁向大數據之路
- Visual FoxPro數據庫程序設計
- 面向對象分析與設計(第3版)