# APIs and Services Basics

Quick apps enable to use of built-in and external services and APIs in a modular way.

See the list of available services.

In the case of the built-in services, you need to declare the specific APIs your app uses in the manifest, so the system will be able to include the libraries in the compilation phase.

For instance, if your app uses the calendar API:

{
    "features": [
        { "name": "system.calendar" }
    ]
}

Since the services and APIs are based on JavaScript modules, they are exported and imported using the standard export and import keywords on the app scripts.

For instance, if you are using the Fetch API:

import fetch from "@system.fetch"

# Types of API functions

The APIs may include four types of functions:

  • synchronous methods,
  • asynchronous methods,
  • callback functions, and
  • asynchronous callback functions.

# Synchronous methods

A synchronous method is a function that directly returns the result (of any type).

For details, please refer to the concrete API reference.

Example of a synchronous method (app.getInfo()):

console.log(JSON.stringify(app.getInfo()))

# Asynchronous methods

An asynchronous method is a function that doesn't return the result directly, so the execution of the code continues in different threads instead of waiting for the result. When the method ends the execution, it runs a series of callback functions.

There are two types of asynchronous call functions, asynchronous callback functions, and Promises.

# Asynchronous Callbacks

Quick app asynchronous methods include the following callback functions.

# success(data)

This function is called after a successful execution.

Parameters:

  • data (type depends on the concrete API)
# fail(data, code)

This function is called after a failure in the execution.

Parameters:

  • data (type depends on the concrete API). Indicates the type of error.
  • code (number). This parameter indicates an error code. Unless otherwise stated, 200 is returned. Other error codes must be defined in the API reference.
# cancel(data)

This function is called when the task is canceled.

Parameters:

  • data (type depends on the concrete API)

The parameter indicates the execution result, which is generally empty. For details, please refer to the API reference.

# complete()

This function is called once the method completes its execution (it could be either success or failure).

TIP

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 always executed.

Example:

prompt.showContextMenu({ 
  itemList: ['item1', 'item2'], 
  itemColor: '#ff33ff', 
  success(data) { 
    console.log('handling callback'); 
  }, 
  fail(data, code) { 
    console.log(`handling fail, code= ${code}`); 
  }, 
  cancel(data) { 
    console.log('handling cancel'); 
  }, 
  complete() { 
    console.log('handling complete'); 
  }, 
})

# Promises

Asynchronous methods support Promises, which enable asynchronous programming for higher readability and better control.

WARNING

Promises cannot be used in quick app widgets.

If the asynchronous method doesn't receive callback functions (success, fail, cancel, or complete), the method returns a Promise object.

For instance, the following example using the system.device API:

<script>
  import device from '@system.device' 
  export default {
    onInit() {
      device.getDeviceId().then((res) => { console.log(res) }).catch(err => err) 
    },
  }
</script>

In the previous example, the value returned by device.getDeviceId() is a Promise object.

If the method execution is successful, the returning object includes a {data} object with the concrete information.

In the previous example, a successful output would be:

{"data":{"deviceId":"ef6b11f-7XXX-21f7-fbcf-a3fb234b4a30"}}

You can also use res.code to get the error code in case of failure.

WARNING

If you want to use the await method, you must add @babel/runtime/regenerator first:

const injectRef = Object.getPrototypeOf(global) || global; 
// injection regeneratorRuntime 
injectRef.regeneratorRuntime = require('@babel/runtime/regenerator');

# Callbacks

Like an asynchronous method, a callback method does not return the execution result directly. After its execution, it runs a callback function you defined instead. Unlike an asynchronous method, a callback API may have several functions as a result.

The APIs with methods supporting callbacks define the following callback functions:

  • callback(data)
  • fail(data)

# callback(data)

This function is executed once the result is obtained, which may be called multiple times.

Parameters:

  • data (its type depends on the concrete API)

# fail(data)

This function is executed in case of failure. This may be launched only once.

Parameters:

  • data (its type depends on the concrete API)

Example:

  • Using geolocation.subscribe to listen to geographical location changes. The system will run the given callback function with the new location after the value changes.
  • If the user refuses to grant the location permission, the system will launch the fail callback function, ending the execution.
geolocation.subscribe({ 
  callback(ret) {
    console.log("handling callback");
  }, 
  fail(data, code) { 
    console.log(`handling fail, code= ${code}`); 
  } 
})

# Asynchronous Callbacks

Like an asynchronous method, an asynchronous callback function doesn't return the result directly. It calls a proper callback function you define.

The difference from an asynchronous method is that an asynchronous callback function only accepts one callback function, and it can be only called once.

# callback(data)

Parameters:

  • data (its type depends on the concrete API)

For instance:

alipay.pay({ 
  orderInfo: "order1", 
  callback: function(ret) { console.log("handling callback"); } 
})

# Result Codes

Most of the APIs use the following codes to indicate the result of the execution of a function.

  • 200: Common error.
  • 201: The operation is rejected by a user.
  • 202: A parameter is invalid.
  • 203: A service is unavailable.
  • 204: A request timed out.