【发布时间】:2020-08-10 10:54:04
【问题描述】:
如果另一个函数返回为真,我有一个应该运行的函数:
// in utils.js
methods:{
funcOne(){
// do some thing
return true
}
}
//in component.vue
methods:{
funcTwo(){
let x = this.funcOne()
if(x){
// do something
}else{
// do something
}
}
}
我该怎么做?由于 js 是运行时的,它不会等待funcOne() 的结果,我知道我应该使用Promise 或async/await。但不知道怎么做!!
更新
我按照建议做了,但仍然没有工作,所以要解释一下情况:
我正在使用sweet alert。如果我的sweet alert 得到确认,它应该发送一个 axios 请求。这是代码:
utils.js 是一个全局添加的 mixins
async function sweetAlert(options) {
// options: method('callback') , icon, title, text, callback, cValue
if (options.method === 'confirm' || options.method === 'callback') {
this.$swal({
icon: options.icon,
title: options.title,
text: options.text,
showCancelButton: true,
cancelButtonText: this.lang.cancel,
confirmButtonText: this.lang.confirm
}).then(async (result) => {
if (result.value) {
if (options.method === 'callback') {
let res = await options.callback(options.cValue)
return res
}
return true
}
})
}
}
我的组件脚本:
let res = await this.sweetAlert({
method: ALERT_METHOD[2], // it is 'confirm'
icon: ALERT_TYPE[2], // it is warning
title: this.lang.deactivate, // added globally
text: this.lang.deactivate_warning, // added globally
})
if (res) {
this.activeSwitchDis = true // in my data
this.activeChanged = true // in my data
// this.axiosGet is a globally adde this.axios.get
let response = await this.axiosGet(`product/deactive/${this.editProduct.pId}`)
// this.resOk is globally added and check for 200
if (this.resOk(response.status)) {
// these are my data and funcs no prob with theme
this.changeError(false)
this.active = false
this.activeChanged = false
this.activeSwitchDis = false
this.setEditProductActive(this.active)
} else {
// these are my data and funcs no prob with theme
this.active = true
this.activeChanged = false
this.activeSwitchDis = false
}
}
问题只是如果我确认 sweetAlert 必须运行 axios
【问题讨论】:
-
funcOne 不是异步函数,它似乎没有返回承诺。
标签: javascript vue.js vuejs2 nuxt.js