codecamp

单次I/O任务开发指导

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

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

    1. import fs from '@ohos.file.fs';
    2. import common from '@ohos.app.ability.common';
    3. async function write(data: string, file: fs.File): Promise<void> {
    4. fs.write(file.fd, data).then((writeLen: number) => {
    5. console.info('write data length is: ' + writeLen)
    6. }).catch((err) => {
    7. console.error(`Failed to write data. Code is ${err.code}, message is ${err.message}`);
    8. })
    9. }
  2. 采用异步能力调用单次I/O任务。示例中的filePath的获取方式请参见获取应用文件路径

    1. async function testFunc(): Promise<void> {
    2. let context = getContext() as common.UIAbilityContext;
    3. let filePath: string = context.filesDir + "/test.txt"; // 应用文件路径
    4. let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
    5. write('Hello World!', file).then(() => {
    6. console.info('Succeeded in writing data.');
    7. }).catch((err) => {
    8. console.error(`Failed to write data. Code is ${err.code}, message is ${err.message}`);
    9. })
    10. fs.close(file);
    11. }
    12. testFunc();
异步并发概述
多线程并发概述
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录
HAR

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }