uniapp:使用Promise簡化回調


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

參考:
在微信小程序中使用 async/await

微信小程序:使用Promise簡化回調


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM