mPaaS exposes two JSAPI calling patterns for Mini Program developers: event listener APIs and object-parameter APIs.
Description
mPaaS JSAPIs fall into two calling patterns. Choose the pattern based on how the API is named.
Event listener APIs (my.on* / my.off*)
APIs prefixed with my.on subscribe to system events. Each takes a callback function as its only parameter. When the event fires, the callback function is called.
To unsubscribe a specific listener, pass the same callback function to the corresponding my.off API. To remove all listeners at once, call the my.off API with no arguments.
Page({
onLoad() {
this.callback = this.callback.bind(this);
my.onBLECharacteristicValueChange(this.callback);
},
onUnload() {
// Remove monitoring when the page is unloaded
my.offBLECharacteristicValueChange(this.callback);
},
callback(res) {
console.log(res);
},
});
Object-parameter APIs
All other JSAPIs accept an object as their only parameter. The object supports three optional callback fields:
success: called when the API call succeedsfail: called when the API call failscomplete: called on both success and failure
The callback result is an object unless the API documentation specifies otherwise. If the result contains an error or errorMessage field, the call failed.
These APIs also return a promise object. The promise resolves with the same result object passed to the success callback — that is, res1 === res2 in the example below.
my.httpRequest({
url: '/x.htm',
success:(res1) => {
},
}).then((res2) => {
// res1 === res2
},(res2) => {
console.log(res.error, res.errorMessage);
})