外观
回调转 Promise
基于回调的 API 使用时可考虑将其转 Promise 后再使用,这样就可避免回调嵌套过深影响了阅读和理解,而且 Promise 线性的表达方式更符合大脑对任务步骤的规划。
蓝牙示例
uni-app 提供的蓝牙相关 API 都是基于回调的,低功耗蓝牙连接流程如下:
- 初始化蓝牙模块
openBluetoothAdapter() - 搜寻附近的蓝牙设备
startBluetoothDevicesDiscovery() - 监听寻找到新设备的事件
onBluetoothDeviceFound() - 用户点击某个蓝牙进行连接时停止蓝牙搜寻
stopBluetoothDevicesDiscovery() - 连接低功耗蓝牙
createBLEConnection() - 获取该蓝牙设备所有服务
getBLEDeviceServices() - 获取指定服务中的所有特征值
getBLEDeviceCharacteristics() - 订阅指定特征值
notifyBLECharacteristicValueChange() - 监听特征值变化事件
onBLECharacteristicValueChange()
如果使用回调方式来书写该流程,则会有多层回调嵌套,即便将各步骤抽取成函数,也不便于理解和维护,特别是代码量增多时,需要上下翻阅跳转到不同的代码块进行阅读。
回调封装
可将回调封装为基于 Promise 的函数,接收一个函数,返回一个新函数,这个新函数会返回一个 Promise。
uni-app 的 API 接收一个对象,对象 success 属性为成功的回调,fail 属性为失败的回调。
js
function promiseWrap(fn) {
return function(obj = {}) {
return new Promise((resolve, reject) => {
fn.call(this, { ...obj, success: resolve, fail: reject })
})
}
}用 promiseWrap() 函数转换各 API,多数 Promise 库也会提供类似 promiseWrap() 这样的辅助函数。
js
// bluetooth.js
const openBluetoothAdapter = promiseWrap(uni.openBluetoothAdapter)
const startBluetoothDevicesDiscovery = promiseWrap(uni.startBluetoothDevicesDiscovery)
const stopBluetoothDevicesDiscovery = promiseWrap(uni.stopBluetoothDevicesDiscovery)
const onBluetoothDeviceFound = uni.onBluetoothDeviceFound
const closeBluetoothAdapter = promiseWrap(uni.closeBluetoothAdapter)
const createBLEConnection = promiseWrap(uni.createBLEConnection)
const getBLEDeviceServices = promiseWrap(uni.getBLEDeviceServices)
const getBLEDeviceCharacteristics = promiseWrap(uni.getBLEDeviceCharacteristics)
const notifyBLECharacteristicValueChange = promiseWrap(uni.notifyBLECharacteristicValueChange)
const onBLECharacteristicValueChange = promiseWrap(uni.onBLECharacteristicValueChange)
export default {
openBluetoothAdapter,
startBluetoothDevicesDiscovery,
stopBluetoothDevicesDiscovery,
onBluetoothDeviceFound,
closeBluetoothAdapter,
createBLEConnection,
getBLEDeviceServices,
getBLEDeviceCharacteristics,
notifyBLECharacteristicValueChange,
onBLECharacteristicValueChange
}使用示意
Promise 线性、同步的书写方式可以一目了然地看到整个流程。
js
import bluetooth from './bluetooth.js'
// 假设点击页面某个按钮开始搜索周边蓝牙
function clickHandler() {
bluetooth
.openBluetoothAdapter()
.then(() => bluetooth.startBluetoothDevicesDiscovery())
.then(() => bluetooth.onBluetoothDeviceFound())
.then(res => console.log('展示获取到的蓝牙设备:', res))
.catch(error => console.log(error))
}
// 用户点击连接某个蓝牙时
function connectDevice() {
bluetooth.stopBluetoothDevicesDiscovery()
bluetooth
.createBLEConnection()
.then(() => bluetooth.getBLEDeviceServices())
.then(() => bluetooth.getBLEDeviceCharacteristics())
.then(() => bluetooth.notifyBLECharacteristicValueChange())
.then(() => bluetooth.onBLECharacteristicValueChange())
.then(res => console.log('特征值变化,相当于设备发来消息', res.value))
.catch(error => console.log(error))
}也可使用异步函数:
js
import bluetooth from './bluetooth.js'
async function clickHandler() {
try{
await bluetooth.openBluetoothAdapter()
await bluetooth.startBluetoothDevicesDiscovery()
await bluetooth.onBluetoothDeviceFound()
} catch (error) {
error => console.log(error)
}
}
async function connectDevice() {
try {
bluetooth.stopBluetoothDevicesDiscovery()
await bluetooth.createBLEConnection()
await bluetooth.getBLEDeviceServices()
await bluetooth.getBLEDeviceCharacteristics()
await bluetooth.notifyBLECharacteristicValueChange()
await bluetooth.onBLECharacteristicValueChange()
} catch (error) {
error => console.log(error)
}
}