There are four types of APIs: synchronous API, asynchronous API, callback, and asynchronous callback. Different APIs provide different capabilities.
A synchronous API directly returns the calling result. The result can be of any type. For details, please refer to the API reference. The following is an example:
console.log(JSON.stringify(app.getInfo()))
An asynchronous API does not return the calling result directly. It, however, calls a proper callback function you defined when a task ends. There are two asynchronous call methods available: asynchronous API callback and Promise, where Promise is supported in versions later than 1010. The following table lists the callback functions supported by asynchronous APIs.
Callback Function | Parameter | Type | Description |
|---|---|---|---|
success | data | any | Execution result, which can be of any type. For details, please refer to the API reference. |
fail | data | any | Callback upon failure. This parameter indicates error information, which can be a character string or of another data type. For details, please refer to the API reference. |
code | number | Callback upon failure. This parameter indicates an error code. Unless otherwise stated, 200 is returned. Other error codes must be defined in the API reference. | |
cancel | data | any | Callback upon cancellation. Some APIs that require user interactions may provide this callback function. This parameter indicates the execution result, which is generally left empty. For details, please refer to the API reference. |
complete | N/A | N/A | Callback upon completion. |
The three callback functions success, fail, and cancel are mutually exclusive. One of them will be called based on the execution result. When this callback is complete, the complete function is then executed.
The following is an example:
prompt.showContextMenu({
itemList: ['item1', 'item2'],
itemColor: '#ff33ff',
success: function(data) {
console.log("handling callback");
},
fail: function(data, code) {
console.log("handling fail, code=" + code);
},
cancel: function(data) {
console.log("handling cancel");
},
complete: function() {
console.log("handling complete");
},
}) An asynchronous API supports Promise, which enables asynchronous programming for higher readability and better control.
This is not applicable to cards.
If no callback function (success, fail, cancel, or complete) is passed during an API call, a Promise object will be returned, based on which you can process the API call result.
The following uses the system.device API as an example:
async function testAsync(){
try{
let res = await device.getDeviceId()
console.debug("get device id " + JSON.stringify(res.data))
}catch(err){
console.log("get device id error " + e.code )
}
} The value returned by the device.getDeviceId() API is a Promise object. You can use await to obtain the successful call result and use catch to obtain the failure result. If an API is successfully called, the res object (res = {data}) is returned. You can use res.data to obtain the result returned by the API and use res.code to obtain the error code returned when the API fails to be called.
If you use the catch method for each API, the code will be cumbersome. You are advised to use one catching function to simplify the code.
function catching(promise){
return promise.then(res =>res).catch(err =>err)
}
var ret = await catching(device.getDeviceId()) When any callback function is passed during an API call, the API will not return Promise but will return the execution result as defined in the asynchronous callback mode.
The asynchronous await API is totally supported in the quick app engine 1040 or later versions. If the engine version configured in minPlatformVersion in the manifest.json file is earlier than 1040, perform the following operations to use await.
Inject @babel/runtime/regenerator into the app.ux file. Sample code:
// This operation is required only if the engine version configured in minPlatformVersion is earlier than 1040.
const injectRef = Object.getPrototypeOf(global) || global;
// injection regeneratorRuntime
injectRef.regeneratorRuntime = require('@babel/runtime/regenerator'); Like an asynchronous API, a callback API does not return the execution result directly. It calls a proper callback function you defined instead. Unlike an asynchronous API, a callback API may call callback functions more than once to return the execution results. The following table lists the callback functions supported by callback APIs.
Callback Function | Parameter | Type | Description |
|---|---|---|---|
callback | data | any | Callback is performed each time the result is obtained, which may be called back multiple times. Execution result, which can be of any type. For details, please refer to the API reference. |
fail | data | any | Callback upon failure. Once this function is called, no more callback function will be called and the API call ends. Call result, which is generally a character string describing the error. Other data types are also supported. For details, please refer to the API reference. |
Take the geographical location API (system.geolocation) as an example.
geolocation.subscribe({
callback:function(ret){console.log("handling callback");},
fail: function(data, code) {
console.log("handling fail, code=" + code);
}
}) Like an asynchronous API, an asynchronous callback API does not return the execution result directly. It calls a proper callback function you defined instead.
Different from an asynchronous API, an asynchronous callback API accepts only one callback. The API call result will be determined based on the callback result. The callback function is called only once.
The following table lists the callback functions supported by asynchronous callback APIs.
Callback Function | Parameter | Type | Description |
|---|---|---|---|
callback | data | any | Callback is performed each time the result is obtained, which may be called back multiple times. Execution result, which can be of any type. For details, please refer to the API reference. |
alipay.pay({
orderInfo:"order1",
callback:function(ret){console.log("handling callback");}
}) Except for synchronous APIs, the asynchronous, callback, and asynchronous callback APIs do not return execution results directly after being called. Instead, they execute a callback function based on the API execution result. In addition, the page where the API is called may be different from the page where the callback function is executed.
Assume that the page called by the API is A. When the callback function is executed, the actual situation may be one of the following:
The callback function needs to check the page status based on the following attributes and take the proper action accordingly: $valid and $visible (Boolean data type)
// Indicates whether a page is valid (not destroyed). this.$valid // Indicates whether a page is in the background. this.$visible
For example, to display the list of merchants at the current geographical location of a user, you need to call the geolocation.getLocation() API to obtain the current location information and then call the fetch.fetch() API to obtain the merchants. When implementing the callback function of geolocation.getLocation(), you need to check the status of the current page and take an action accordingly.
The sample code is as follows:
geolocation.getLocation({
success:function(data){
if (this.$valid && this.$visible) {
// The page is being displayed.
}
else if (this.$valid && !this.$visible) {
// The page is in the background.
}
else {
// The page is being destroyed.
}
}.bind(this),
fail: function(data, code) {
console.log("handling fail, code=" + code);
}
}) The callback function can be called multiple times by the callback API. If the callback function is repeatedly called after the page is switched to the background or destroyed, the app response will become slow and memory leaks may occur. Therefore, you are advised to use either of the following methods to cancel the call:
Method 1 is recommended as it can cancel a call promptly and prevent resource waste.
For example, for a page that calls the geolocation.subscribe function to record a user's trajectory:
The logic for canceling the call by using method 1 is as follows:
The sample code is as follows:
export default {
onDestroy () {
geolocation.unsubscribe()
},
record() {
geolocation.getLocation({
success:function(data){
if (this.$valid && this.$visible) {
// The page is being displayed, and the trajectory is recorded.
}
else if (this.$valid && !this.$visible) {
// The page is in the background and the trajectory is recorded.
}
else {
// The page is being destroyed and does not need to be processed.
}
}.bind(this),
fail: function(data, code) {
console.log("handling fail, code=" + code);
}
})
}
} The logic for canceling the call by using method 2 is as follows:
The sample code is as follows:
geolocation.getLocation({
success:function(data){
if (this.$valid && this.$visible) {
// The page is being displayed, and the trajectory is recorded.
}
else if (this.$valid && !this.$visible) {
// The page is in the background and the trajectory is recorded.
}
else {
// The page is being destroyed.
geolocation.unsubscribe()
}
}.bind(this),
fail: function(data, code) {
console.log("handling fail, code=" + code);
}
}) This method can be used in the lifecycle callback function of an app. It is independent of the page where the API is called. Therefore, it is valid as long as the app is running. However, we strongly recommend that you cancel a callback when confirming that the API needs not be called.