I am facing an issue with running a function based on the return value of another function:
// 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
}
}
}
Can someone guide me on how to achieve this? Since JavaScript is runtime, it does not wait for the result of funcOne()
. I believe I should implement Promise
or async/await
, but I'm unsure of the correct approach.
UPDATE
After following the suggestions provided, I still couldn't get it to work. Let me explain the scenario:
I have integrated sweet alert
functionality. If a confirmation is received from the sweet alert, an axios request should be sent. Here is the code snippet:
utils.js serves as a globally added 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
}
})
}
}
Code snippet in my component script:
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
}
}
The issue lies in ensuring that the axios call is only made upon confirming the sweet alert.