# API Overview

The js APIs of uni-app consist of two parts: standard ECMAScript js APIs and uni extension APIs.

Standard ECMAScript js is just the fundamental js. Browsers extend it with objects like window, document, navigator. Mini-programs also extend standard js with APIs such as wx.xx, my.xx, swan.xx. Node extends it with modules such as fs.

uni-app extends ECMAScript with the uni object, and the API naming remains compatible with mini-programs.

# Differences between Standard js and Browser js

The js code of uni-app runs in the browser for web platforms. On non-web platforms (including mini-programs and App), Android runs in the v8 engine, iOS runs in the native jscore engine, and does not run in a browser or webview.

On non-web platforms, browser js APIs such as window, document, navigator are not supported, but standard ECMAScript is supported.

Please note that browser js is not equivalent to standard js.

Therefore, uni-app's non-web platforms also support standard js, including syntax like if, for, variable types such as strings, numbers, dates, booleans, arrays, custom objects, and their processing methods. Only browser-specific objects such as window, document, navigator are not supported.

# Platform-specific API Calls

In addition to the cross-platform APIs built into the uni-app framework, platform-specific APIs can also be freely used via conditional compilation.

Refer to each platform's development documentation for specific API specifications. For App-side JS APIs, refer to html5plus.org; uni-app also supports enhancing App-side development capabilities with native plugins, see plugin development documentation.

When a new API is added to a platform, developers can use it directly without upgrading uni-app.

Platform-specific API fields, such as payType and paymentChannel in Kuaishou mini-program's ks.pay, can be passed directly during API calls and will be forwarded to the respective platform's API.

# Additional Notes

  • APIs starting with uni.on are event listener APIs, which accept a CALLBACK function as a parameter. When the event is triggered, the CALLBACK function will be called.
  • Unless otherwise specified, other API interfaces accept an OBJECT as a parameter.
  • The OBJECT can specify success, fail, and complete to receive the results of the API call.
  • Platform Differences If not otherwise specified, all platforms are supported.
  • Asynchronous APIs return the errMsg field, while synchronous APIs do not. For example, getSystemInfoSync does not include errMsg in the return value.

# API Promisification

  1. Specific strategies for API promisification:
  • For asynchronous methods, if success, fail, complete and other callback parameters are not provided, the data will be returned as a Promise. For example: uni.getImageInfo()

  • Asynchronous methods that return an object: if you want to get the returned object, you must pass at least one callback parameter (success, fail, complete), for example:

     // Normal usage
     const task = uni.connectSocket({
      success(res){
       console.log(res)
      }
     })
    
     // Promisified usage
     uni.connectSocket().then(res => {
       // This is the 'res' returned from the success callback in normal usage
       // Normally, uni.connectSocket returns a task object. If you need the task object, do not use promise style.
       console.log(res)
     })
    
  1. APIs that are not promisified:
  • Synchronous methods (ending with sync), e.g.: uni.getSystemInfoSync()
  • Methods starting with create, e.g.: uni.createMapContext()
  • Methods ending with manager, e.g.: uni.getBackgroundAudioManager()

# API Promisification in Vue 2 and Vue 3

The return format for API Promisification differs between Vue 2 and Vue 3 projects. Below are the differences and how to convert between the formats.

  • Differences

    • Vue 2 wraps some APIs with Promises, returning an array where the first item is the error object and the second item is the data. In this case, using catch does not catch errors because errors are intercepted internally.
    • Vue 3 wraps some APIs with Promises, a successful call triggers the then callback, while a failed call triggers the catch callback.

    Usage Example:

    Vue2

    Vue 3

    // Default usage
    uni.request({
      url: "https://www.example.com/request",
      success: (res) => {
        console.log(res.data);
      },
      fail: (err) => {
        console.error(err);
      },
    });
    
    // Promise
    uni
      .request({
        url: "https://www.example.com/request",
      })
      .then((data) => {
        // 'data' is an array
        // First item is error info, i.e. the fail callback
        // Second item is the returned data
        var [err, res] = data;
        console.log(res.data);
      });
    
    // Await
    async function request() {
      var [err, res] = await uni.request({
        url: "https://www.example.com/request",
      });
      console.log(res.data);
    }
    
  • Converting Return Formats

Vue2

Vue3

// Convert Vue 2 to Vue 3: Add the following code to main.js
function isPromise(obj) {
  return (
    !!obj &&
    (typeof obj === "object" || typeof obj === "function") &&
    typeof obj.then === "function"
  );
}

uni.addInterceptor({
  returnValue(res) {
    if (!isPromise(res)) {
      return res;
    }
    return new Promise((resolve, reject) => {
      res.then((res) => {
        if (!res) {
          resolve(res);
          return;
        }
        if (res[0]) {
          reject(res[0]);
        } else {
          resolve(res[1]);
        }
      });
    });
  },
});