背景:点击一个按钮需要知道点击的用户是否有权限进行下一步操作,因为有多个地方要用来验验证权限,所以把检查函数Check抽取出来,在另一个页面,函数Check中有axios请求,想要知道是否满足权限需要后端返回, 当满足权限时需要进行下一步操作。
问题:是否进行下一步需要经过axios请求后告知,是异步操作。
解决方式:使用async和await
第一次处理:
import { Modal, Message } from 'antd'
import http from '../services/http'// 包装axios
function Check() {
const data = {}
http.post('xxx', '', data).then((res) => {
const { isSuccess, result, message } = res.data
if (!isSuccess) {
Message.info(message)
return false
}
if (!result) {
Modal.info({
title: message,
centered: true,
okText: '确定'
})
return false
} else {
return true
}
})
}
export default Check
其他地方调用:
import Check from 'xxx'
// 点击按钮的处理函数
clickButton() {
// 检查权限
const flag = Check()
// 返回的flag为promise
}
返回的结果为promise需要使用 .then()取得值进行判断,使用之后发现结果是undefined,因为Check函数没有返回值,需要再次处理
经过处理后Check函数:
import { Modal, Message } from 'antd'
import http from '../services/http'// 包装axios
async function Check() {
const data = {}
const checkFlag = await http.post('xxx', '', data).then((res) => {
const { isSuccess, result, message } = res.data
if (!isSuccess) {
Message.info(message)
return false
}
if (!result) {
Modal.info({
title: message,
centered: true,
okText: '确定'
})
return false
} else {
return true
}
})
return checkFlag
}
export default Check
引用的地方:
// 点击按钮的处理函数
clickButton() {
// 检查权限
const flag = Check()
flag.then((res) => {
// res为返回的checkFlag
if (res) {
this.nextOperation()
}
})
}