官术网_书友最值得收藏!

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.

Writing the static version

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.

主站蜘蛛池模板: 兴仁县| 金山区| 界首市| 沛县| 哈巴河县| 砀山县| 蕲春县| 云龙县| 固原市| 闻喜县| 临泉县| 滁州市| 张北县| 乌兰察布市| 濮阳市| 濮阳县| 定陶县| 姜堰市| 桐乡市| 大石桥市| 安国市| 仁布县| 连州市| 瑞安市| 南投县| 平顶山市| 丹东市| 陆良县| 隆化县| 黎城县| 林州市| 武安市| 临颍县| 扎囊县| 额尔古纳市| 石棉县| 彰武县| 伊金霍洛旗| 徐闻县| 西乡县| 沧州市|