4 回答

TA貢獻(xiàn)1946條經(jīng)驗 獲得超3個贊
啥也不廢話,直接上代碼:
getCode(){
// 我覺得帳號驗證和圖片驗證可以并行:
Promise.all([
this.$post('賬號驗證api',{phone:this.phone}).then(res => {
if (!res.success) throw new Error('帳號非法')
}),
this.$post('圖片驗證api',{imgCode:this.imgCode}).then(res=>{
if (!res.success) throw new Error('圖片驗證碼非法')
}),
]).then(() => {
// 一定要注意return!
return this.$post('短信驗證api',{SMSCode:this.Code}).then(res=>{
if (!res.success) throw new Error("短信驗證碼非法!")
})
}).then(() => {
// 繼續(xù)正常流程處理
}).catch((err) => {
// 處理異常,比如彈框:
alert(err)
})
}
其實用async/await來寫更爽:
async getCode(){
try {
// 我覺得帳號驗證和圖片驗證可以并行:
await Promise.all([
this.$post('賬號驗證api',{phone:this.phone}).then(res => {
if (!res.success) throw new Error('帳號非法')
}),
this.$post('圖片驗證api',{imgCode:this.imgCode}).then(res=>{
if (!res.success) throw new Error('圖片驗證碼非法')
}),
])
const res = await this.$post('短信驗證api',{SMSCode:this.Code})
if (!res.success) {
throw new Error("短信驗證碼非法!")
}
// 繼續(xù)正常流程處理...
} catch (err) {
// 處理異常,比如彈框:
alert(err)
}
}
對了,其實前端還可以做更多事情:
手機號碼格式校驗
圖片驗證碼校驗
當(dāng)然這兩個校驗肯定服務(wù)端也要做,前端做用戶體驗會更好(速度更快)一些。
關(guān)于圖片驗證碼校驗,還要再啰嗦一下,別把圖片驗證碼直接返回給前端,而是應(yīng)該返回個hash值(最好加鹽后的hash值)到前端,然后前端校驗用戶輸入的驗證碼的hash值與后臺返回的hash值是否一樣,不一樣就報錯。

TA貢獻(xiàn)1864條經(jīng)驗 獲得超6個贊
1.我覺得手機驗證可以在前端完成,沒必要傳到后臺驗證。這樣就可以少一個post
2.如果一定都要在前端,可以用Promise,我覺得可以稍微優(yōu)雅一點,類似于
let phonePro = new Promise(...),imgPro = new Promise(...);
Promise.all([phonePro,imgPro]).then(res=>{
//res是一個數(shù)組
if(res[0].success && res[1].success){
...//發(fā)送短信
}
})
看不懂上面可以看MDN-Promise,相關(guān)api介紹

TA貢獻(xiàn)1805條經(jīng)驗 獲得超9個贊
一個接口就夠了:發(fā)送短信驗證碼的接口,把用戶名(手機號)、圖像驗證碼參數(shù)都帶上,先驗證這倆參數(shù),如果沒問題,就直接發(fā)短信;如果有問題就報錯。
沒有必要先調(diào)用兩次接口,分別校驗兩個參數(shù)。
添加回答
舉報