我們來嘗試使用Promise。
1、需求,做個抽獎的按鈕,
抽獎規則:
30%的幾率中獎,中獎會提示恭喜恭喜,獎品為10萬?RMB?勞斯萊斯優惠券,沒中獎會提示再接再厲。
2、先搭界面:
<view class="title">抽獎規則:</view>
<view class="content">30%的幾率中獎,中獎會提示恭喜恭喜,獎品為10萬 RMB 勞斯萊斯優惠券,沒中獎會提示再接再厲。</view>
<button class="btn" bind:tap="prizeDraw">開始抽獎</button>
3、css文件
page {height: 100vh;display: flex;flex-direction: column;justify-content: center;
}
.btn{margin-top: 50rpx;color: black;border: 1px solid black;
}.title{margin: 10rpx 40rpx;font-size: 50rpx;font-weight: 550;
}.content{margin: 20rpx 80rpx;font-size: 40rpx;
}
3、實現prizeDraw函數。
prizeDraw(){const?p?=?new?Promise((resolve,reject)?=>?{setTimeout(()?=>?{let?n?=?Math.floor(Math.random()*100)+1;if?(n?<=?30)?{resolve();}?else?{reject();}},?1000);});p.then(()?=>?{wx.showModal({title:?'恭喜恭喜',content:?'獎品為?10?萬?RMB?勞斯萊斯優惠券',showCancel:?false,?//?隱藏取消按鈕confirmText:?'我知道了',});},()?=>?{wx.showModal({title:?'沒抽中',content:?'再接再厲',showCancel:?false,?//?隱藏取消按鈕confirmText:?'我知道了',});});}
代碼說明:
a、const?p?=?new?Promise() ; //生成Promise對象。
b、里面有個參數,是函數,寫法() => {}
c、函數里面有兩個方法,resolve(解決)和reject(拒絕),函數里面的邏輯結果成功就調用resolve,失敗就調用reject 。
d、然后運行Promise對象的then函數。
e、then里面帶兩個函數參數。
f、第一個用來執行成功的后續步驟,比如彈框之類,第二個用來執行失敗的后續步驟