• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 单次I/O任务开发指导 (Promise和async/await)
2
3
4Promise和async/await提供异步并发能力,适用于单次I/O任务的场景开发,本文以使用异步进行单次文件写入为例来提供指导。
5
6
71. 实现单次I/O任务逻辑。
8
9    ```ts
10    import fs from '@ohos.file.fs';
11    import { BusinessError } from '@ohos.base';
12    import common from '@ohos.app.ability.common';
13
14    async function write(data: string, file: fs.File): Promise<void> {
15      fs.write(file.fd, data).then((writeLen: number) => {
16        console.info('write data length is: ' + writeLen)
17      }).catch((err: BusinessError) => {
18        console.error(`Failed to write data. Code is ${err.code}, message is ${err.message}`);
19      })
20    }
21    ```
222. 采用异步能力调用单次I/O任务。示例中的filePath的获取方式请参见[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)。
23
24    ```ts
25    async function testFunc(): Promise<void>  {
26      let context = getContext() as common.UIAbilityContext;
27      let filePath: string = context.filesDir + "/test.txt"; // 应用文件路径
28      let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
29      write('Hello World!', file).then(() => {
30        console.info('Succeeded in writing data.');
31        fs.close(file);
32      }).catch((err: BusinessError) => {
33        console.error(`Failed to write data. Code is ${err.code}, message is ${err.message}`);
34        fs.close(file);
35      })
36    }
37    testFunc();
38    ```
39