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>