2 回答
TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊
因?yàn)?js 是運(yùn)行時(shí)的,所以它不會等待結(jié)果
funcOne()
由于funcOne() 您的示例代碼中的不是異步函數(shù),因此這是不正確的:調(diào)用將等待函數(shù)完成并返回其值。
我怎樣才能做到這一點(diǎn)?[...] 我知道我應(yīng)該使用 Promise 或
async/await. 但不知道怎么辦!!
那么你最好閱讀Promises 的文檔和函數(shù)的async/await語法,因?yàn)槟阈枰獙λ鼈冇姓_的理解才能有效地使用它。
更新
現(xiàn)在到你的實(shí)際代碼:你的實(shí)現(xiàn)sweetAlert()實(shí)際上并沒有返回任何東西,因?yàn)?code>returns 的范圍是另一個(gè)函數(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實(shí)際上作用于傳遞給then()處理程序的函數(shù)。該鏈將返回另一個(gè) 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
})
}
}
請注意,如果它進(jìn)入第一個(gè)塊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貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超3個(gè)贊
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
}
}
}
添加回答
舉報(bào)
