From c2d7c98438588a9b3b1f651396392d2da57a2dc9 Mon Sep 17 00:00:00 2001 From: Gloria Date: Mon, 5 Jun 2023 17:15:10 +0800 Subject: [PATCH] fixed 49e95ad from https://gitee.com/wusongqing/docs/pulls/19198 Update docs against 18363+18380+18295+18835+18855+18838 Signed-off-by: wusongqing --- .../apis/js-apis-app-ability-appManager.md | 124 +++++++-- .../reference/apis/js-apis-medialibrary.md | 240 +++++++++++------- .../reference/apis/js-apis-reminderAgent.md | 58 ++--- .../apis/js-apis-reminderAgentManager.md | 4 +- .../reference/apis/js-apis-taskpool.md | 159 ++++++------ .../reference/apis/js-apis-worker.md | 156 ++++++------ 6 files changed, 411 insertions(+), 330 deletions(-) diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appManager.md b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md index 6be97f26f8..9fa26885cc 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-appManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md @@ -22,9 +22,9 @@ Checks whether this application is undergoing a stability test. This API uses an **Parameters** -| Type| Description| -| -------- | -------- | -|AsyncCallback<boolean> |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.| + | Type| Description| + | -------- | -------- | + |AsyncCallback<boolean> |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.| **Error codes** @@ -59,9 +59,9 @@ Checks whether this application is undergoing a stability test. This API uses a **Return value** -| Type| Description| -| -------- | -------- | -| Promise<boolean> | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.| + | Type| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.| **Error codes** @@ -94,9 +94,9 @@ Checks whether this application is running on a RAM constrained device. This API **Return value** -| Type| Description| -| -------- | -------- | -| Promise<boolean> | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.| + | Type| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.| **Error codes** @@ -128,9 +128,9 @@ Checks whether this application is running on a RAM constrained device. This API **Parameters** -| Type| Description| -| -------- | -------- | -| AsyncCallback<boolean> |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.| + | Type| Description| + | -------- | -------- | + | AsyncCallback<boolean> |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.| **Error codes** @@ -164,9 +164,9 @@ Obtains the memory size of this application. This API uses a promise to return t **Return value** -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.| + | Type| Description| + | -------- | -------- | + | Promise<number> | Promise used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.| **Error codes** @@ -198,9 +198,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb **Parameters** -| Type| Description| -| -------- | -------- | -|AsyncCallback<number> |Callback used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.| + | Type| Description| + | -------- | -------- | + |AsyncCallback<number> |Callback used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.| **Error codes** @@ -298,6 +298,82 @@ appManager.getRunningProcessInformation((err, data) => { }); ``` +## appManager.isSharedBundleRunning + +isSharedBundleRunning(bundleName: string, versionCode: number): Promise\; + +Checks whether the shared library is in use. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| bundleName | string | Yes | Bundle name of the shared library.| +| versionCode | number | Yes | Version number of the shared library. | + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result. The value **true** means that the shared library is in use, and **false** means the opposite.| + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.isSharedBundleRunning(bundleName, versionCode).then((data) => { + console.log('The shared bundle running is: ${JSON.stringify(data)}'); +}).catch((error) => { + console.error('error: ${JSON.stringify(error)}'); +}); +``` + +## appManager.isSharedBundleRunning + +isSharedBundleRunning(bundleName: string, versionCode: number, callback: AsyncCallback\): void; + +Checks whether the shared library is in use. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| bundleName | string | Yes | Bundle name of the shared library.| +| versionCode | number | Yes | Version number of the shared library. | + +**Return value** + +| Type| Description| +| -------- | -------- | +|AsyncCallback\> | Callback used to return the result. The value **true** means that the shared library is in use, and **false** means the opposite.| + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.isSharedBundleRunning(bundleName, versionCode, (err, data) => { + if (err) { + console.error('err: ${JSON.stringify(err)}'); + } else { + console.log('The shared bundle running is: ${JSON.stringify(data)}'); + } +}); +``` + ## appManager.on on(type: 'applicationState', observer: ApplicationStateObserver): number; @@ -641,7 +717,7 @@ Obtains applications that are running in the foreground. This API uses a promise | Type| Description| | -------- | -------- | -| Promise\> | Promise used to return an array holding the application state data. | +| Promise\> | Promise used to return an array holding the application state data.| **Error codes** @@ -731,11 +807,11 @@ Kills a process by bundle name and account ID. This API uses an asynchronous cal **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | Yes| Bundle name.| + | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + | callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index c90acd7d15..4d7cc79018 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -77,7 +77,6 @@ let media = mediaLibrary.getMediaLibrary(); ### getFileAssets7+ - getFileAssets(options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void Obtains file assets (also called files). This API uses an asynchronous callback to return the result. @@ -105,7 +104,7 @@ async function example() { selectionArgs: [imageType.toString()], }; // Obtain the files in asynchronous callback mode. - media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => { + media.getFileAssets(imagesFetchOp, async (error, fetchFileResult) => { // Check whether the result set of the obtained files is undefined. If yes, the API call fails. if (fetchFileResult == undefined) { console.error('get fetchFileResult failed with error: ' + error); @@ -124,8 +123,8 @@ async function example() { return; } console.info('Get fetchFileResult successfully, count: ' + count); - // Obtain the first file in the result set in asynchronous callback mode. - fetchFileResult.getFirstObject((error, fileAsset) => { + // Obtain the first file in the result set in asynchronous callback mode. If there are a large number of files, use getAllObject instead. + fetchFileResult.getFirstObject(async (error, fileAsset) => { // Check whether the first file is undefined. If yes, the API call fails. if (fileAsset == undefined) { console.error('get first object failed with error: ' + error); @@ -178,7 +177,7 @@ async function example() { selectionArgs: [imageType.toString()], }; // Obtain the files in promise mode. - media.getFileAssets(imagesFetchOp).then((fetchFileResult) => { + media.getFileAssets(imagesFetchOp).then(async (fetchFileResult) => { // Obtain the total number of files in the result set. const count = fetchFileResult.getCount(); // Check whether the number is less than 0. If yes, the API call fails. @@ -192,8 +191,8 @@ async function example() { return; } console.info('Get fetchFileResult successfully, count: ' + count); - // Obtain the first file in the result set in promise mode. - fetchFileResult.getFirstObject().then((fileAsset) => { + // Obtain the first file in the result set in promise mode. If there are a large number of files, use getAllObject instead. + fetchFileResult.getFirstObject().then(async (fileAsset) => { console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName); // Call getNextObject to obtain the next file until the last one. for (let i = 1; i < count; i++) { @@ -514,17 +513,18 @@ Obtains the albums. This API uses an asynchronous callback to return the result. ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - media.getAlbums(AlbumNoArgsfetchOp, (error, albumList) => { - if (albumList != undefined) { - console.info('getAlbums successfully: ' + JSON.stringify(albumList)); - } else { - console.error('getAlbums failed with error: ' + error); - } - }) + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + media.getAlbums(AlbumNoArgsfetchOp, (error, albumList) => { + if (albumList != undefined) { + console.info('getAlbums successfully: ' + JSON.stringify(albumList)); + } else { + console.error('getAlbums failed with error: ' + error); + } + }) } ``` @@ -554,15 +554,16 @@ Obtains the albums. This API uses a promise to return the result. ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - media.getAlbums(AlbumNoArgsfetchOp).then((albumList) => { - console.info('getAlbums successfully: ' + JSON.stringify(albumList)); - }).catch((error) => { - console.error('getAlbums failed with error: ' + error); - }); + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + media.getAlbums(AlbumNoArgsfetchOp).then((albumList) => { + console.info('getAlbums successfully: ' + JSON.stringify(albumList)); + }).catch((error) => { + console.error('getAlbums failed with error: ' + error); + }); } ``` @@ -2021,7 +2022,7 @@ async function example() { ### getNextObject7+ - getNextObject(callback: AsyncCallback<FileAsset>): void +getNextObject(callback: AsyncCallback<FileAsset>): void Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result. > **NOTE** @@ -2049,7 +2050,8 @@ async function example() { }; let fetchFileResult = await media.getFileAssets(getImageOp); let fileAsset = await fetchFileResult.getFirstObject(); - if (!fileAsset.isAfterLast) { + console.log('fetchFileResult getFirstObject successfully, displayName: ' + fileAsset.displayName); + if (!fetchFileResult.isAfterLast()) { fetchFileResult.getNextObject((error, fileAsset) => { if (error) { console.error('fetchFileResult getNextObject failed with error: ' + error); @@ -2065,7 +2067,7 @@ async function example() { ### getNextObject7+ - getNextObject(): Promise<FileAsset> +getNextObject(): Promise<FileAsset> Obtains the next file asset in the result set. This API uses a promise to return the result. > **NOTE** @@ -2093,7 +2095,8 @@ async function example() { }; let fetchFileResult = await media.getFileAssets(getImageOp); let fileAsset = await fetchFileResult.getFirstObject(); - if (!fileAsset.isAfterLast) { + console.log('fetchFileResult getFirstObject successfully, displayName: ' + fileAsset.displayName); + if (!fetchFileResult.isAfterLast()) { fetchFileResult.getNextObject().then((fileAsset) => { console.info('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName); fetchFileResult.close(); @@ -2369,20 +2372,21 @@ Commits the modification in the album attributes to the database. This API uses ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - const albumList = await media.getAlbums(AlbumNoArgsfetchOp); - const album = albumList[0]; - album.albumName = 'hello'; - album.commitModify((error) => { - if (error) { - console.error('commitModify failed with error: ' + error); - return; - } - console.info('commitModify successful.'); - }) + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const album = albumList[0]; + album.albumName = 'hello'; + album.commitModify((error) => { + if (error) { + console.error('commitModify failed with error: ' + error); + return; + } + console.info('commitModify successful.'); + }) } ``` @@ -2406,18 +2410,60 @@ Commits the modification in the album attributes to the database. This API uses ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - const albumList = await media.getAlbums(AlbumNoArgsfetchOp); - const album = albumList[0]; - album.albumName = 'hello'; - album.commitModify().then(() => { - console.info('commitModify successfully'); - }).catch((error) => { - console.error('commitModify failed with error: ' + error); - }); + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const album = albumList[0]; + album.albumName = 'hello'; + album.commitModify().then(() => { + console.info('commitModify successfully'); + }).catch((error) => { + console.error('commitModify failed with error: ' + error); + }); +} +``` + +### getFileAssets7+ + +getFileAssets(callback: AsyncCallback<FetchFileResult>): void + +Obtains the file assets in this album. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.READ_MEDIA + +**System capability**: SystemCapability.Multimedia.MediaLibrary.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ----------------------------------- | +| callback | AsyncCallback<[FetchFileResult](#fetchfileresult7)> | Yes | Callback used to return the file assets.| + +**Example** + +```js +async function example() { + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + // Obtain the albums that meet the retrieval options and return the album list. + const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const album = albumList[0]; + // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. + album.getFileAssets((error, fetchFileResult) => { + if (error) { + console.error('album getFileAssets failed with error: ' + error); + return; + } + let count = fetchFileResult.getCount(); + console.info('album getFileAssets successfully, count: ' + count); + fetchFileResult.close(); + }); } ``` @@ -2442,27 +2488,28 @@ Obtains the file assets in this album. This API uses an asynchronous callback to ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - let fileNoArgsfetchOp = { - selections: '', - selectionArgs: [], + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + let fileNoArgsfetchOp = { + selections: '', + selectionArgs: [], + } + // Obtain the albums that meet the retrieval options and return the album list. + const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const album = albumList[0]; + // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. + album.getFileAssets(fileNoArgsfetchOp, (error, fetchFileResult) => { + if (error) { + console.error('album getFileAssets failed with error: ' + error); + return; } - // Obtain the albums that meet the retrieval options and return the album list. - const albumList = await media.getAlbums(AlbumNoArgsfetchOp); - const album = albumList[0]; - // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. - album.getFileAssets(fileNoArgsfetchOp, (error, fetchFileResult) => { - if (error) { - console.error('album getFileAssets failed with error: ' + error); - return; - } - let count = fetchFileResult.getCount(); - console.info('album getFileAssets successfully, count: ' + count); - fetchFileResult.close(); - }); + let count = fetchFileResult.getCount(); + console.info('album getFileAssets successfully, count: ' + count); + fetchFileResult.close(); + }); } ``` @@ -2492,25 +2539,26 @@ Obtains the file assets in this album. This API uses a promise to return the res ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - let fileNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - // Obtain the albums that meet the retrieval options and return the album list. - const albumList = await media.getAlbums(AlbumNoArgsfetchOp); - const album = albumList[0]; - // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. - album.getFileAssets(fileNoArgsfetchOp).then((fetchFileResult) => { - let count = fetchFileResult.getCount(); - console.info('album getFileAssets successfully, count: ' + count); - fetchFileResult.close(); - }).catch((error) => { - console.error('album getFileAssets failed with error: ' + error); - }); + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + let fileNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + // Obtain the albums that meet the retrieval options and return the album list. + const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const album = albumList[0]; + // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. + album.getFileAssets(fileNoArgsfetchOp).then((fetchFileResult) => { + let count = fetchFileResult.getCount(); + console.info('album getFileAssets successfully, count: ' + count); + fetchFileResult.close(); + }).catch((error) => { + console.error('album getFileAssets failed with error: ' + error); + }); } ``` diff --git a/en/application-dev/reference/apis/js-apis-reminderAgent.md b/en/application-dev/reference/apis/js-apis-reminderAgent.md index dc0a33ab0c..0c7fa19432 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgent.md @@ -20,9 +20,7 @@ import reminderAgent from'@ohos.reminderAgent'; ## reminderAgent.publishReminder(deprecated) -```ts publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\): void -``` Publishes a reminder through the reminder agent. This API uses an asynchronous callback to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). @@ -39,7 +37,7 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| - | callback | AsyncCallback\ | Yes| Callback used to return the published reminder's ID.| + | callback | AsyncCallback\ | Yes| Callback used to return the published reminder's ID.| **Example** ```ts @@ -56,9 +54,7 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c ## reminderAgent.publishReminder(deprecated) -```ts publishReminder(reminderReq: ReminderRequest): Promise\ -``` Publishes a reminder through the reminder agent. This API uses a promise to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). @@ -78,7 +74,7 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu **Return value** | Type| Description| | -------- | -------- | - | Promise\ | Promise used to return the published reminder's ID.| + | Promise\ | Promise used to return the published reminder's ID.| **Example** ```ts @@ -95,9 +91,7 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu ## reminderAgent.cancelReminder(deprecated) -```ts cancelReminder(reminderId: number, callback: AsyncCallback\): void -``` Cancels the reminder with the specified ID. This API uses an asynchronous callback to return the cancellation result. @@ -112,7 +106,7 @@ Cancels the reminder with the specified ID. This API uses an asynchronous callba | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderId | number | Yes| ID of the reminder to cancel. The value is obtained by calling [publishReminder](#reminderagentpublishreminder).| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -125,9 +119,7 @@ reminderAgent.cancelReminder(1, (err, data) => { ## reminderAgent.cancelReminder(deprecated) -```ts cancelReminder(reminderId: number): Promise\ -``` Cancels the reminder with the specified ID. This API uses a promise to return the cancellation result. @@ -147,7 +139,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** @@ -159,9 +151,7 @@ reminderAgent.cancelReminder(1).then(() => { ## reminderAgent.getValidReminders(deprecated) -```ts getValidReminders(callback: AsyncCallback\>): void -``` Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the reminders. @@ -175,7 +165,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback\\> | Yes| Callback used to return an array of all valid reminders set by the current application.| +| callback | AsyncCallback\> | Yes| Callback used to return an array of all valid reminders set by the current application.| **Example** @@ -209,9 +199,7 @@ reminderAgent.getValidReminders((err, reminders) => { ## reminderAgent.getValidReminders(deprecated) -```ts getValidReminders(): Promise\> -``` Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the reminders. @@ -225,7 +213,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Type| Description| | -------- | -------- | -| Promise\\> | Promise used to return an array of all valid reminders set by the current application.| +| Promise\> | Promise used to return an array of all valid reminders set by the current application.| **Example** @@ -259,9 +247,7 @@ reminderAgent.getValidReminders().then((reminders) => { ## reminderAgent.cancelAllReminders(deprecated) -```ts cancelAllReminders(callback: AsyncCallback\): void -``` Cancels all reminders set by the current application. This API uses an asynchronous callback to return the cancellation result. @@ -275,7 +261,7 @@ Cancels all reminders set by the current application. This API uses an asynchron | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -288,9 +274,7 @@ reminderAgent.cancelAllReminders((err, data) =>{ ## reminderAgent.cancelAllReminders(deprecated) -```ts cancelAllReminders(): Promise\ -``` Cancels all reminders set by the current application. This API uses a promise to return the cancellation result. @@ -304,7 +288,7 @@ Cancels all reminders set by the current application. This API uses a promise to | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** @@ -316,9 +300,7 @@ reminderAgent.cancelAllReminders().then(() => { ## reminderAgent.addNotificationSlot(deprecated) -```ts addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback\): void -``` Adds a notification slot. This API uses an asynchronous callback to return the result. @@ -333,7 +315,7 @@ Adds a notification slot. This API uses an asynchronous callback to return the r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -351,9 +333,7 @@ reminderAgent.addNotificationSlot(mySlot, (err, data) => { ## reminderAgent.addNotificationSlot(deprecated) -```ts addNotificationSlot(slot: NotificationSlot): Promise\ -``` Adds a notification slot. This API uses a promise to return the result. @@ -373,7 +353,7 @@ Adds a notification slot. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** @@ -391,9 +371,7 @@ reminderAgent.addNotificationSlot(mySlot).then(() => { ## reminderAgent.removeNotificationSlot(deprecated) -```ts removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback): void -``` Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result. @@ -408,7 +386,7 @@ Removes a notification slot of a specified type. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -423,9 +401,7 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, ## reminderAgent.removeNotificationSlot(deprecated) -```ts removeNotificationSlot(slotType: notification.SlotType): Promise -``` Removes a notification slot of a specified type. This API uses a promise to return the result. @@ -445,7 +421,7 @@ Removes a notification slot of a specified type. This API uses a promise to retu | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** @@ -568,7 +544,6 @@ Defines the reminder to publish. ## ReminderRequestCalendar(deprecated) -ReminderRequestCalendar extends ReminderRequest Defines a reminder for a calendar event. @@ -581,13 +556,12 @@ Defines a reminder for a calendar event. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dateTime | [LocalDateTime](#localdatetime) | Yes| Reminder time.| -| repeatMonths | Array\ | No| Month in which the reminder repeats.| -| repeatDays | Array\ | No| Date on which the reminder repeats.| +| repeatMonths | Array\ | No| Month in which the reminder repeats.| +| repeatDays | Array\ | No| Date on which the reminder repeats.| ## ReminderRequestAlarm(deprecated) -ReminderRequestAlarm extends ReminderRequest Defines a reminder for an alarm. @@ -601,13 +575,11 @@ Defines a reminder for an alarm. | -------- | -------- | -------- | -------- | | hour | number | Yes| Hour portion of the reminder time.| | minute | number | Yes| Minute portion of the reminder time.| -| daysOfWeek | Array\ | No| Days of a week when the reminder repeats. The value ranges from 1 to 7, corresponding to the data from Monday to Sunday.| +| daysOfWeek | Array\ | No| Days of a week when the reminder repeats. The value ranges from 1 to 7, corresponding to the data from Monday to Sunday.| ## ReminderRequestTimer(deprecated) -ReminderRequestTimer extends ReminderRequest - Defines a reminder for a scheduled timer. > **NOTE** diff --git a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md index 7ec9eeb2c2..87a8ea3167 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md @@ -170,7 +170,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th | Type| Description| | -------- | -------- | -| PPromise\ | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Error codes** @@ -611,7 +611,7 @@ Defines the reminder to publish. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderType | [ReminderType](#remindertype) | Yes| Type of the reminder.| -| actionButton10+ | [ActionButton](#actionbutton) | No| Button displayed for the reminder in the notification panel. For common applications, a maximum of two buttons are supported. For system applications, a maximum of two buttons are supported in API version 9, and a maximum of three buttons are supported in API version 10 and later versions. | +| actionButton10+ | [ActionButton](#actionbutton) | No| Button displayed for the reminder in the notification panel. For common applications, a maximum of two buttons are supported. For system applications, a maximum of two buttons are supported in API version 9, and a maximum of three buttons are supported in API version 10 and later versions.| | wantAgent | [WantAgent](#wantagent) | No| Information about the ability that is redirected to when the reminder is clicked.| | maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.| | ringDuration | number | No| Ringing duration, in seconds. The default value is **1**.| diff --git a/en/application-dev/reference/apis/js-apis-taskpool.md b/en/application-dev/reference/apis/js-apis-taskpool.md index 4eb81b7153..6de1a67d7a 100644 --- a/en/application-dev/reference/apis/js-apis-taskpool.md +++ b/en/application-dev/reference/apis/js-apis-taskpool.md @@ -1,10 +1,10 @@ -# @ohos.taskpool (Using the Task Pool) +# @ohos.taskpool (Starting the Task Pool) The task pool provides a multi-thread running environment for applications. It helps reduce resource consumption and improve system performance. It also frees you from caring about the lifecycle of thread instances. You can use the **TaskPool** APIs to create background tasks and perform operations on them, for example, executing or canceling a task. Theoretically, you can create an unlimited number of tasks, but this is not recommended for memory considerations. In addition, you are not advised performing blocking operations in a task, especially indefinite blocking. Long-time blocking operations occupy worker threads and may block other task scheduling, adversely affecting your application performance. -You can determine the execution sequence of tasks with the same priority. They are executed in the same sequence as you call the task execution APIs. The default task priority is **MEDIUM**. (The task priority mechanism is not supported yet.) +You can determine the execution sequence of tasks with the same priority. They are executed in the same sequence as you call the task execution APIs. The default task priority is **MEDIUM**. -If the number of tasks to be executed is greater than the number of worker threads in the task pool, the task pool scales out based on load balancing to minimize the waiting duration. Similarly, when the number of tasks to be executed falls below the number of worker threads, the task pool scales in to reduce the number of worker threads. (The load balancing mechanism is not supported yet.) +If the number of tasks to be executed is greater than the number of worker threads in the task pool, the task pool scales out based on load balancing to minimize the waiting duration. Similarly, when the number of tasks to be executed falls below the number of worker threads, the task pool scales in to reduce the number of worker threads. The **TaskPool** APIs return error codes in numeric format. For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). @@ -32,13 +32,13 @@ Enumerates the priorities available for created tasks. **Example** ```ts -function func(args) { - "use concurrent"; - console.log("func: " + args); +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let task = new taskpool.Task(func, 100); +async function taskpoolPriority() { + let task = new taskpool.Task(printArgs, 100); let highCount = 0; let mediumCount = 0; @@ -65,7 +65,7 @@ async function taskpoolTest() { }) } } -taskpoolTest(); +taskpoolPriority(); ``` ## Task @@ -99,12 +99,12 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ```ts @Concurrent -function func(args) { - console.log("func: " + args); +function printArgs(args) { + console.log("printArgs: " + args); return args; } -let task = new taskpool.Task(func, "this is my first Task"); +let task = new taskpool.Task(printArgs, "this is my first Task"); ``` ### Attributes @@ -151,17 +151,17 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ```ts @Concurrent -function func(args) { - console.log("func: " + args); +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let value = await taskpool.execute(func, 100); +async function taskpoolExecute() { + let value = await taskpool.execute(printArgs, 100); console.log("taskpool result: " + value); } -taskpoolTest(); +taskpoolExecute(); ``` ## taskpool.execute @@ -199,18 +199,18 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ```ts @Concurrent -function func(args) { - console.log("func: " + args); +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let task = new taskpool.Task(func, 100); +async function taskpoolExecute() { + let task = new taskpool.Task(printArgs, 100); let value = await taskpool.execute(task); console.log("taskpool result: " + value); } -taskpoolTest(); +taskpoolExecute(); ``` ## taskpool.cancel @@ -239,14 +239,14 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example of successful task cancellation** ```ts -function func(args) { - "use concurrent"; - console.log("func: " + args); +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let task = new taskpool.Task(func, 100); +async function taskpoolCancel() { + let task = new taskpool.Task(printArgs, 100); taskpool.execute(task); try { taskpool.cancel(task); @@ -255,20 +255,20 @@ async function taskpoolTest() { } } -taskpoolTest(); +taskpoolCancel(); ``` **Example of a failure to cancel a task that has been executed** ```ts -function func(args) { - "use concurrent"; - console.log("func: " + args); +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let task = new taskpool.Task(func, 100); +async function taskpoolCancel() { + let task = new taskpool.Task(printArgs, 100); let value = taskpool.execute(task); let start = new Date().getTime(); while (new Date().getTime() - start < 1000) {// Wait for 1s to ensure that the task has been executed. @@ -282,25 +282,25 @@ async function taskpoolTest() { } } -taskpoolTest(); +taskpoolCancel(); ``` **Example of a failure to cancel an ongoing task** ```ts -function func(args) { - "use concurrent"; - console.log("func: " + args); +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let task1 = new taskpool.Task(func, 100); - let task2 = new taskpool.Task(func, 200); - let task3 = new taskpool.Task(func, 300); - let task4 = new taskpool.Task(func, 400); - let task5 = new taskpool.Task(func, 500); - let task6 = new taskpool.Task(func, 600); +async function taskpoolCancel() { + let task1 = new taskpool.Task(printArgs, 100); + let task2 = new taskpool.Task(printArgs, 200); + let task3 = new taskpool.Task(printArgs, 300); + let task4 = new taskpool.Task(printArgs, 400); + let task5 = new taskpool.Task(printArgs, 500); + let task6 = new taskpool.Task(printArgs, 600); let res1 = taskpool.execute(task1); let res2 = taskpool.execute(task2); @@ -315,7 +315,7 @@ async function taskpoolTest() { } } -taskpoolTest(); +taskpoolCancel(); ``` ## Additional Information @@ -327,7 +327,7 @@ The following sequenceable data types are supported: All Primitive Type (excludi - The task pool APIs can be used only in the module with **compileMode** set to **esmodule** in the stage model. To check the **compileMode** setting of a module, open the **build-profile.json5** file of the module and check for **"compileMode": "esmodule"** under **buildOption**. - A task in the task pool can reference only variables passed in by input parameters or imported variables, rather than closure variables. The decorator **@Concurrent** is used to intercept unsupported variables. - A task in the task pool supports only common functions or async functions, rather than class member functions or anonymous functions. The decorator **@Concurrent** is used to intercept unsupported functions. -- The decorator **@Concurrent** can be used only in the .ets file. To create a task in the task pool in the .ts file, use the statement **use concurrent**. +- The decorator **@Concurrent** can be used only in .ets files. ### Using the Task Pool in Simple Mode @@ -336,23 +336,23 @@ The following sequenceable data types are supported: All Primitive Type (excludi ```ts // Common functions are supported, and variables passed in by input parameters are also supported. @Concurrent -function func(args) { +function printArgs(args) { console.log("func: " + args); return args; } -async function taskpoolTest() { +async function taskpoolExecute() { // taskpool.execute(task) - let task = new taskpool.Task(func, "create task, then execute"); + let task = new taskpool.Task(printArgs, "create task, then execute"); let val1 = await taskpool.execute(task); console.log("taskpool.execute(task) result: " + val1); // taskpool.execute(function) - let val2 = await taskpool.execute(func, "execute task by func"); + let val2 = await taskpool.execute(printArgs, "execute task by func"); console.log("taskpool.execute(function) result: " + val2); } -taskpoolTest(); +taskpoolExecute(); ``` **Example 2** @@ -367,24 +367,24 @@ export var c = 2000; import { c } from "./b"; @Concurrent -function test(a) { +function printArgs(a) { console.log(a); console.log(c); return a; } -async function taskpoolTest() { +async function taskpoolExecute() { // taskpool.execute(task) - let task = new taskpool.Task(test, "create task, then execute"); + let task = new taskpool.Task(printArgs, "create task, then execute"); let val1 = await taskpool.execute(task); console.log("taskpool.execute(task) result: " + val1); // taskpool.execute(function) - let val2 = await taskpool.execute(test, "execute task by func"); + let val2 = await taskpool.execute(printArgs, "execute task by func"); console.log("taskpool.execute(function) result: " + val2); } -taskpoolTest(); +taskpoolExecute(); ``` **Example 3** @@ -392,57 +392,52 @@ taskpoolTest(); ```ts // The async functions are supported. @Concurrent -async function task() { +async function delayExcute() { let ret = await Promise.all([ new Promise(resolve => setTimeout(resolve, 1000, "resolved")) ]); return ret; } -async function taskpoolTest() { - taskpool.execute(task).then((result) => { +async function taskpoolExecute() { + taskpool.execute(delayExcute).then((result) => { console.log("TaskPoolTest task result: " + result); }); } -taskpoolTest(); +taskpoolExecute(); ``` **Example 4** ```ts -// Use use concurrent to create a task in the task pool in the .ts file. -// c.ts -function test1(n) { - "use concurrent" - return n; +// c.ets +@Concurrent +function strSort(inPutArr) { + let newArr = inPutArr.sort(); + return newArr; } -export async function taskpoolTest1() { - console.log("taskpoolTest1 start"); - var task = new taskpool.Task(test1, 100); +export async function func1() { + console.log("taskpoolTest start"); + let strArray = ['c test string', 'b test string', 'a test string']; + var task = new taskpool.Task(strSort, strArray); var result = await taskpool.execute(task); - console.log("taskpoolTest1 result:" + result); + console.log("func1 result:" + result); } -async function test2() { - "use concurrent" - var ret = await Promise.all([ - new Promise(resolve => setTimeout(resolve, 1000, "resolved")) - ]); - return ret; -} -export async function taskpoolTest2() { +export async function func2() { console.log("taskpoolTest2 start"); - taskpool.execute(test2).then((result) => { - console.log("TaskPoolTest2 result: " + result); + let strArray = ['c test string', 'b test string', 'a test string']; + taskpool.execute(strSort, strArray).then((result) => { + console.log("func2 result: " + result); }); } ``` ```ts -/ / a.ets (in the same directory as c.ts) +/ / a.ets (in the same directory as c.ets) import { taskpoolTest1, taskpoolTest2 } from "./c"; -taskpoolTest1(); -taskpoolTest2(); +func1(); +func2(); ``` diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md index 490e283c36..7c74cdefce 100644 --- a/en/application-dev/reference/apis/js-apis-worker.md +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -83,9 +83,9 @@ import worker from '@ohos.worker'; // Create a Worker instance. // In the FA model, the workers directory is at the same level as the pages directory in the entry module. -const workerFAModel01 = new worker.ThreadWorker("workers/worker.js", {name:"first worker in FA model"}); +const workerFAModel01 = new worker.ThreadWorker("workers/worker.ts", {name:"first worker in FA model"}); // In the FA model, the workers directory is at the same level as the parent directory of the pages directory in the entry module. -const workerFAModel02 = new worker.ThreadWorker("../workers/worker.js"); +const workerFAModel02 = new worker.ThreadWorker("../workers/worker.ts"); // In the stage model, the workers directory is at the same level as the pages directory in the entry module. const workerStageModel01 = new worker.ThreadWorker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"}); @@ -872,13 +872,13 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); workerInstance.onmessage = function(e) { // let data = e.data; - console.log("receive data from worker.js"); + console.log("receive data from worker.ts"); } ``` @@ -920,13 +920,13 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); workerInstance.onmessage = function(e) { // let data = e.data; - console.log("receive data from worker.js"); + console.log("receive data from worker.ts"); } ``` @@ -936,7 +936,7 @@ import worker from '@ohos.worker'; const workerPort = worker.workerPort; workerPort.onmessage = function(e){ // let data = e.data; - workerPort.postMessage("receive data from main.js"); + workerPort.postMessage("receive data from main thread"); } ``` @@ -960,7 +960,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); ``` @@ -1002,7 +1002,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); @@ -1013,7 +1013,7 @@ workerInstance.postMessage("hello world"); import worker from '@ohos.worker'; const workerPort = worker.workerPort; workerPort.onmessage = function(e) { - console.log("receive main.js message"); + console.log("receive main thread message"); } ``` @@ -1045,7 +1045,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); ``` @@ -1055,7 +1055,7 @@ const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); import worker from '@ohos.worker'; const parentPort = worker.workerPort; parentPort.onmessageerror = function(e) { - console.log("worker.js onmessageerror") + console.log("worker.ts onmessageerror") } ``` @@ -1130,7 +1130,7 @@ Defines the event handler to be called when an exception occurs during worker ex **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts") ``` @@ -1140,7 +1140,7 @@ const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts") import worker from '@ohos.worker'; const workerPort = worker.workerPort workerPort.onerror = function(e){ - console.log("worker.js onerror") + console.log("worker.ts onerror") } ``` @@ -1193,9 +1193,9 @@ import worker from '@ohos.worker'; // Create a Worker instance. // In the FA model, the workers directory is at the same level as the pages directory. -const workerFAModel01 = new worker.Worker("workers/worker.js", {name:"first worker in FA model"}); +const workerFAModel01 = new worker.Worker("workers/worker.ts", {name:"first worker in FA model"}); // In the FA model, the workers directory is at the same level as the parent directory of the pages directory. -const workerFAModel02 = new worker.Worker("../workers/worker.js"); +const workerFAModel02 = new worker.Worker("../workers/worker.ts"); // In the stage model, the workers directory is at the same level as the pages directory. const workerStageModel01 = new worker.Worker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"}); @@ -1275,7 +1275,7 @@ Sends a message to the worker thread. The data type of the message must be seque **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); var buffer = new ArrayBuffer(8); workerInstance.postMessage(buffer, [buffer]); @@ -1302,7 +1302,7 @@ Sends a message to the worker thread. The data type of the message must be seque **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.postMessage("hello world"); @@ -1332,7 +1332,7 @@ Adds an event listener for the worker thread. This API provides the same functio **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.on("alert", (e)=>{ console.log("alert listener callback"); }) @@ -1360,7 +1360,7 @@ Adds an event listener for the worker thread and removes the event listener afte **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.once("alert", (e)=>{ console.log("alert listener callback"); }) @@ -1388,7 +1388,7 @@ Removes an event listener for the worker thread. This API provides the same func **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); // Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener. workerInstance.off("alert"); ``` @@ -1408,7 +1408,7 @@ Terminates the worker thread to stop it from receiving messages. **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.terminate(); ``` @@ -1433,7 +1433,7 @@ Defines the event handler to be called when the worker thread exits. The handler **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.onexit = function(e) { console.log("onexit"); } @@ -1467,7 +1467,7 @@ Defines the event handler to be called when an exception occurs during worker ex **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.onerror = function(e) { console.log("onerror"); } @@ -1489,12 +1489,12 @@ Defines the event handler to be called when the host thread receives a message s | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------------------- | -| event | [MessageEvent](#messageeventt) | Yes | Message received.| +| event | [MessageEvent](#messageeventt)| Yes | Message received.| **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.onmessage = function(e) { // e: MessageEvent. The usage is as follows: // let data = e.data; @@ -1518,12 +1518,12 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------- | -| event | [MessageEvent](#messageeventt) | Yes | Error data.| +| event | [MessageEvent](#messageeventt)| Yes | Error data.| **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.onmessageerror= function(e) { console.log("onmessageerror"); } @@ -1555,7 +1555,7 @@ Adds an event listener for the worker thread. This API provides the same functio **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -1583,7 +1583,7 @@ Removes an event listener for the worker thread. This API provides the same func **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -1617,7 +1617,7 @@ Dispatches the event defined for the worker thread. **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is not supported yet. ``` @@ -1625,7 +1625,7 @@ workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is n The **dispatchEvent** API can be used together with the **on**, **once**, and **addEventListener** APIs. The sample code is as follows: ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); // Usage 1: workerInstance.on("alert_on", (e)=>{ @@ -1677,7 +1677,7 @@ Removes all event listeners for the worker thread. **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -1732,17 +1732,17 @@ Sends a message to the host thread from the worker thread. **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.postMessage("hello world"); workerInstance.onmessage = function(e) { // let data = e.data; - console.log("receive data from worker.js"); + console.log("receive data from worker.ts"); } ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e){ @@ -1773,22 +1773,22 @@ Sends a message to the host thread from the worker thread. **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.postMessage("hello world"); workerInstance.onmessage = function(e) { // let data = e.data; - console.log("receive data from worker.js"); + console.log("receive data from worker.ts"); } ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e){ // let data = e.data; - parentPort.postMessage("receive data from main.js"); + parentPort.postMessage("receive data from main thread"); } ``` @@ -1806,12 +1806,12 @@ Terminates the worker thread to stop it from receiving messages. **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e) { @@ -1836,22 +1836,22 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------ | | this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller. | -| ev | [MessageEvent](#messageeventt) | Yes | Message received.| +| ev | [MessageEvent](#messageeventt) | Yes | Message received.| **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.postMessage("hello world"); ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e) { - console.log("receive main.js message"); + console.log("receive main thread message"); } ``` @@ -1872,21 +1872,21 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------- | | this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller.| -| ev | [MessageEvent](#messageeventt) | Yes | Error data.| +| ev | [MessageEvent](#messageeventt)| Yes | Error data.| **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessageerror = function(e) { - console.log("worker.js onmessageerror") + console.log("worker.ts onmessageerror") } ``` @@ -1940,7 +1940,7 @@ Implements event listening. **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -2010,16 +2010,16 @@ Defines the event handler to be called when an exception occurs during worker ex **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js") +const workerInstance = new worker.Worker("workers/worker.ts") ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort parentPort.onerror = function(e){ - console.log("worker.js onerror") + console.log("worker.ts onerror") } ``` @@ -2045,17 +2045,17 @@ Exception: When an object created through a custom class is passed, no serializa > An FA project of API version 9 is used as an example. ```js -// main.js +// Main thread import worker from '@ohos.worker'; -const workerInstance = new worker.ThreadWorker("workers/worker.js"); -workerInstance.postMessage("message from main to worker"); +const workerInstance = new worker.ThreadWorker("workers/worker.ts"); +workerInstance.postMessage("message from main thread to worker"); workerInstance.onmessage = function(d) { // When the worker thread passes obj2, data contains obj2, excluding the Init or SetName method. let data = d.data; } ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const workerPort = worker.workerPort; class MyModel { @@ -2065,7 +2065,7 @@ class MyModel { } } workerPort.onmessage = function(d) { - console.log("worker.js onmessage"); + console.log("worker.ts onmessage"); let data = d.data; let func1 = function() { console.log("post message is function"); @@ -2083,10 +2083,10 @@ workerPort.onmessage = function(d) { workerPort.postMessage(obj2); // No serialization error occurs when passing obj2. } workerPort.onmessageerror = function(e) { - console.log("worker.js onmessageerror"); + console.log("worker.ts onmessageerror"); } workerPort.onerror = function(e) { - console.log("worker.js onerror"); + console.log("worker.ts onerror"); } ``` @@ -2111,15 +2111,10 @@ Each actor concurrently processes tasks of the main thread. For each actor, ther ### FA Model ```js -// main.js (The following assumes that the workers directory and pages directory are at the same level.) +// Main thread (The following assumes that the workers directory and pages directory are at the same level.) import worker from '@ohos.worker'; // Create a Worker instance in the main thread. const workerInstance = new worker.ThreadWorker("workers/worker.ts"); -// Create either a .json or .ts file. -// const workerInstance = new worker.ThreadWorker("workers/worker.js"); - -// In versions earlier than API version 9, use the following to create a Worker instance in the main thread. -// const workerInstance = new worker.Worker("workers/worker.js"); // The main thread transfers information to the worker thread. workerInstance.postMessage("123"); @@ -2128,7 +2123,7 @@ workerInstance.postMessage("123"); workerInstance.onmessage = function(e) { // data carries the information sent by the worker thread. let data = e.data; - console.log("main.js onmessage"); + console.log("main thread onmessage"); // Terminate the Worker instance. workerInstance.terminate(); @@ -2136,7 +2131,7 @@ workerInstance.onmessage = function(e) { // Call onexit(). workerInstance.onexit = function() { - console.log("main.js terminate"); + console.log("main thread terminate"); } ``` ```js @@ -2146,9 +2141,6 @@ import worker from '@ohos.worker'; // Create an object in the worker thread for communicating with the main thread. const workerPort = worker.workerPort -// In versions earlier than API version 9, use the following to create an object in the worker thread for communicating with the main thread. -// const parentPort = worker.parentPort - // The worker thread receives information from the main thread. workerPort.onmessage = function(e) { // data carries the information sent by the main thread. @@ -2176,13 +2168,11 @@ Configuration of the **build-profile.json5** file: ``` ### Stage Model ```js -// main.js (The following assumes that the workers directory and pages directory are at different levels.) +// Main thread (The following assumes that the workers directory and pages directory are at different levels.) import worker from '@ohos.worker'; // Create a Worker instance in the main thread. const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.ts"); -// Create either a .json or .ts file. -// const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.js"); // The main thread transfers information to the worker thread. workerInstance.postMessage("123"); @@ -2191,14 +2181,14 @@ workerInstance.postMessage("123"); workerInstance.onmessage = function(e) { // data carries the information sent by the worker thread. let data = e.data; - console.log("main.js onmessage"); + console.log("main thread onmessage"); // Terminate the Worker instance. workerInstance.terminate(); } // Call onexit(). workerInstance.onexit = function() { - console.log("main.js terminate"); + console.log("main thread terminate"); } ``` ```js -- GitLab