单次iO异步
鸿蒙系统中,Promise和async/await提供异步并发能力,适用于单次I/O任务的场景开发,避免了对主线程的占用,减少了对主线程的阻塞
示例代码
3.1 单次向文件写入字符串的文件IO任务
private async write(data: string, file: fs.File): Promise<void> {
fs.write(file.fd, data).then((writeLen: number) => {
console.info('write data length is: ' + writeLen)
}).catch((err) => {
console.error(`Failed to write data. err is ${err}`);
})
}
3.2 async/await异步能力调用单次I/O任务
async writeTextToFile(): Promise<void> {
let context = getContext() as common.UIAbilityContext;
let filePath: string = context.filesDir + "/test.txt";
let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
this.write('Hello World!', file).then(() => {
console.info('Succeeded in writing data.');
}).catch((err) => {
console.error(`Failed to write data. Code is ${err}`);
throw err
}).finally(() => {
if (file) {
fs.close(file);
}
})
}
3.3 调用
try {
await this.writeTextToFile()
} catch (error) {
console.error('writeTextToFile 执行出错:', error);
}
3.效果
05-25 16:26:50.081 10589-5947 0FEFE/JsApp com.example.base_demo I Succeeded in writing data.
05-25 16:26:50.082 10589-5947 04388/file_api com.example.base_demo I [file_entity.h:46->~FileEntity] Unlock succeeded inode = 123271
05-25 16:26:50.084 10589-5947 0FEFE/JsApp
最后
如果你想快速提升鸿蒙技术,那么可以直接领取这份包含了:【OpenHarmony多媒体技术、Stage模型、ArkUI多端部署、分布式应用开发、音频、视频、WebGL、Napi组件、OpenHarmony内核、Harmony南向开发、鸿蒙项目实战】等技术知识点。
鸿蒙Next全套VIP学习资料←点击领取!(安全链接,放心点击)