2 回答

TA貢獻1906條經(jīng)驗 獲得超3個贊
因為 js 是運行時的,所以它不會等待結(jié)果
funcOne()
由于funcOne()
您的示例代碼中的不是異步函數(shù),因此這是不正確的:調(diào)用將等待函數(shù)完成并返回其值。
我怎樣才能做到這一點?[...] 我知道我應(yīng)該使用 Promise 或
async/await
. 但不知道怎么辦?。?/p>
那么你最好閱讀Promises 的文檔和函數(shù)的async/await
語法,因為你需要對它們有正確的理解才能有效地使用它。
更新
現(xiàn)在到你的實際代碼:你的實現(xiàn)sweetAlert()
實際上并沒有返回任何東西,因為return
s 的范圍是另一個函數(shù):
# abbreviated code:
async function sweetAlert(options) {
if (...) {
this.$swal({...}).then(async (result) => {
if (...) {
let res = await options.callback(options.cValue)
return res
}
return true
})
}
}
所以return res和return true實際上作用于傳遞給then()處理程序的函數(shù)。該鏈將返回另一個 promise,該 promise 將以 thatreturn的值解析。要將此作為sweetAlert()您需要的返回值return:
# abbreviated code:
function sweetAlert(options) {
if (...) {
// return the result of the chain here for sweetAlert()
return this.$swal({...}).then(async (result) => {
if (...) {
let res = await options.callback(options.cValue)
return res
}
return true
})
}
}
請注意,如果它進入第一個塊sweetAlert(),它只會返回一些東西。if另請注意,您不在函數(shù)中使用await(sweetAlert()但僅在其中的其他函數(shù)中使用)并返回 aPromise而不是原始值,您可以省略async它的關(guān)鍵字。
或者,您可以完全使用async/await:
async function sweetAlert(options) {
if (options.method === 'confirm' || options.method === 'callback') {
// await the return value here
let result = await this.$swal({...})
if (result.value) {
if (options.method === 'callback') {
let res = await options.callback(options.cValue)
return res
}
// now this will return from sweetAlert()
return true
}
}
}

TA貢獻1803條經(jīng)驗 獲得超3個贊
methods:{
async funcOne(){
// do some thing
await someAsyncFunctionOrLogic();
return true
}
}
//in component.vue
methods:{
async funcTwo(){
let x = await this.funcOne()
if(x){
// do something
}else{
// do something
}
}
}
添加回答
舉報