2 回答
TA贡献1906条经验 获得超3个赞
因为 js 是运行时的,所以它不会等待结果
funcOne()
由于funcOne() 您的示例代码中的不是异步函数,因此这是不正确的:调用将等待函数完成并返回其值。
我怎样才能做到这一点?[...] 我知道我应该使用 Promise 或
async/await. 但不知道怎么办!!
那么你最好阅读Promises 的文档和函数的async/await语法,因为你需要对它们有正确的理解才能有效地使用它。
更新
现在到你的实际代码:你的实现sweetAlert()实际上并没有返回任何东西,因为returns 的范围是另一个函数:
# 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()处理程序的函数。该链将返回另一个 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另请注意,您不在函数中使用await(sweetAlert()但仅在其中的其他函数中使用)并返回 aPromise而不是原始值,您可以省略async它的关键字。
或者,您可以完全使用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条经验 获得超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
}
}
}
添加回答
举报
