uniapp - api promise化


uniapp很多api都是異步的,而非同步(asyn),舉個例子來說

 

例子1:

  付款步驟:1、2、3,而實際運行可能是1、3、2...

 

 

 

 

例子2:

  通過回調深淵解決它異步問題

 

 

 

例子3:

  uniapp內置async/await,這個的確很棒(封裝了request請求情況就會好很多)- 它們有條不紊的進行着

 

 

 

 

但是請思考,uniapp那么多api且很多都是異步的!!! 因此把它們api promise化是必須的(同步)

 

 

1.復制並且命名它

uniPromise.js

 

export default (callback) => {
	return (object = {}) => {
		return new Promise((resolve, reject) => {
			object.success = (...args) => {
				resolve(...args)
			};
			object.fail = (...args) => {
				reject(...args)
			};
			object.complete = () => {}
			callback(object)
		})
	}
};

  

 

 

2.main.js 導入全局

import uniPromise from './uniPormis.js'

Vue.prototype.$uni = uniPromise;

  

3.使用它

index.vue

 

<template>
	<view>
		uniPromise
	</view>
</template>

<script>
	export default {
		data() {
			return {}
		},
		components: {},
		onLoad() {

			// 示例1
			this.$uni(uni.getSystemInfo)().then(res => {
				console.log(res)
			})
			.then(()=>	this.$uni(uni.showToast)({
				title:'hello'
			}))
			.then(() =>	this.$uni(uni.showLoading)({
                title: '正在保存'
            }))
			.then(()=>	this.$uni(uni.hideLoading)())
			.then(()=>	this.$uni(uni.showModal)({
				title: 'hello',
				content: 'babbabab',
				showCancel: false,
				cancelText: '取消',
				confirmText: '確定'
			}))
			.then(res=>{
				if(res.confirm){
					console.log('按了確定')
				}else{
					console.log('按了取消')
				}
				
			})
			
			
			// uni.showModal({
			// 	title: '',
			// 	content: '',
			// 	showCancel: false,
			// 	cancelText: '',
			// 	confirmText: '',
			// 	success: res => {},
			// 	fail: () => {},
			// 	complete: () => {}
			// });
			
			

			// 示例2
			// this.$uni(uni.showModal)({
			// 	title: 'uniPromise'
			// })
			// .then(res => {
			// 	console.log(res)
			// 	if (res.cancel) {
			// 		// 中斷本次運行
			// 		console.warn('中斷本次運行... 出問題了')
			// 		return Promise.reject('這里填寫出錯的原因,並且中斷它');
			// 	}
			// })
			// .catch(res=>{
			// 	console.log('捕獲以后還能運行.. 不捕獲直接中斷',res);
			// })
			// .then(() => this.$uni(uni.showLoading)({
			// 	title: '正在保存'
			// }))
			// .then(() =>{
			// 	sleep(3000);
			// 	console.log('這里延遲了3s')
			// })
			// .then(() => this.$uni(uni.hideLoading)());
		},
		mounted() {},
		methods: {}
	}

	const sleep = numberMillis => {
		let now = new Date();
		let exitTime = now.getTime() + numberMillis;
		while (true) {
			now = new Date();
			if (now.getTime() > exitTime)
				return;
		}
	}
</script>

<style>
</style>

 

  

 

 


免責聲明!

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



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