single-io-development.md 1.0 KB
Newer Older
G
ge-yafang 已提交
1 2 3 4 5 6 7
# 单次I/O任务开发指导


Promise和async/await提供异步并发能力,适用于单次I/O任务的场景开发,本文以使用异步进行单次文件写入为例来提供指导。


1. 实现单次I/O任务逻辑。
8

G
ge-yafang 已提交
9 10
   ```js
   import fs from '@ohos.file.fs';
11 12 13 14 15
   import { BusinessError } from '@ohos.base';

   async function write(data: string, filePath: string): Promise<void> {
     let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE);
     fs.write(file.fd, data).then((writeLen: number) => {
G
ge-yafang 已提交
16
       fs.close(file);
17
     }).catch((err: BusinessError) => {
G
ge-yafang 已提交
18 19 20 21 22 23
       console.error(`Failed to write data. Code is ${err.code}, message is ${err.message}`);
     })
   }
   ```

2. 采用异步能力调用单次I/O任务。示例中的filePath的获取方式请参见[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)
24

G
ge-yafang 已提交
25
   ```js
26
   let filePath: string = ...; // 应用文件路径
G
ge-yafang 已提交
27 28 29 30
   write('Hello World!', filePath).then(() => {
     console.info('Succeeded in writing data.');
   })
   ```