HarmonyOS 应用开发之@Concurrent装饰器:声明并校验并发函数

本文详细介绍了在HarmonyOS的TaskPool中使用@Concurrent装饰器进行并发函数执行的方法,包括异步和同步函数的示例,以及注意事项,如返回Promise的处理和错误处理。

在使用 TaskPool 时,执行的并发函数需要使用该装饰器修饰,否则无法通过相关校验。

说明:
从API version 9开始,该装饰器支持在ArkTS卡片中使用。

装饰器说明

@Concurrent并发装饰器 说明
装饰器参数 无。
使用场景 仅支持在Stage模型的工程中使用。
装饰的函数类型 允许标注async函数或普通函数。禁止标注generator、箭头函数、method。不支持类成员函数或者匿名函数。
装饰的函数内的变量类型 允许使用local变量、入参和通过import引入的变量。禁止使用闭包变量。
装饰的函数内的返回值类型 支持的类型请查 序列化支持类型。

说明:
并发函数中返回Promise的表现需关注,其中并发同步函数会处理返回该Promise并返回结果。

示例:

import taskpool from '@ohos.taskpool';

@Concurrent
function testPromise(args1: number, args2: number): Promise<number> {
  return new Promise<number>((testFuncA, testFuncB)=>{
    testFuncA(args1 + args2);
  });
}

@Concurrent
async function testPromise1(args1: number, args2: number): Promise<number> {
  return new Promise<number>((testFuncA, testFuncB)=>{
    testFuncA(args1 + args2);
  });
}

@Concurrent
async function testPromise2(args1: number, args2: number): Promise<number> {
  return await new Promise<number>((testFuncA, testFuncB)=>{
    testFuncA(args1 + args2)
  });
}

@Concurrent
function testPromise3() {
  return Promise.resolve(1);
}

@Concurrent
async function testPromise4(): Promise<number> {
  return 1;
}

@Concurrent
async function testPromise5(): Promise<string>
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值