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

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.

主站蜘蛛池模板: 宁化县| 稻城县| 普洱| 内乡县| 平南县| 措美县| 邯郸市| 内丘县| 陇川县| 确山县| 庐江县| 区。| 南澳县| 娱乐| 潍坊市| 衡水市| 金塔县| 揭西县| 邢台市| 舞钢市| 吐鲁番市| 隆安县| 巴里| 兴义市| 太仆寺旗| 钟山县| 台北市| 安丘市| 疏勒县| 积石山| 桂平市| 西安市| 尤溪县| 池州市| 桂东县| 六枝特区| 正镶白旗| 拜泉县| 德兴市| 临海市| 奈曼旗|