uniapp:使用Promise簡化回調
promisify.js
因為異步api都是success和fail的形式,所以封裝方法:
export const promisify = (api) => {
return (options, ...params) => {
return new Promise((resolve, reject) => {
api(Object.assign({}, options, {
success: resolve,
fail: reject
}), ...params);
});
}
}
為簡化之前
uni.getUserProfile({
success: res => {
console.log(res)
},
fail: res => {
},
complete:()=>{
}
})
使用上面的promisify.js
簡化后:
import {promisify} from './promisify.js'
const getSystemInfo = promisify(uni.getSystemInfo)
getUserProfile({
desc: "獲取你的昵稱、頭像、地區及性別",
}).then((res)=>{
console.log(res.userInfo)
}).catch((err)=>{
console.log('拒絕授權')
}).finally(()=>{
console.log('拒絕或授權都會執行')
})
因為uniapp中多很多少異步方法,這樣一個一個轉換不方便const getSystemInfo = promisify(uni.getSystemInfo)
因此批量轉換(promisify.js)
export const promisify = (api) => {
return (options, ...params) => {
return new Promise((resolve, reject) => {
api(Object.assign({}, options, {
success: resolve,
fail: reject
}), ...params);
});
}
}
export const toAPromise = (...names) => {
return (names || [])
.map(name => ({
name,
member: uni[name]
}))
.filter(t => typeof t.member === "function")
.reduce((r, t) => {
r[t.name] = promisify(uni[t.name]);
return r;
}, {});
}
export const unip = toAPromise('getSystemInfo','getUserProfile','login','showToast');
使用
import {unip} from '@/common/js/promisify.js'
unip.getUserProfile({
desc: "獲取你的昵稱、頭像、地區及性別",
}).then((res) => {
console.log(res.userInfo)
}).catch((err) => {
unip.showToast({
title: "拒絕了授權",
icon: "none"
})
}).finally(() => {
console.log('拒絕或授權都會執行')
})
- 多個嵌套可用async/await