gpt4 book ai didi

javascript - 以单行方式从类运行异步/等待函数调用

转载 作者:行者123 更新时间:2023-11-30 11:05:10 25 4
gpt4 key购买 nike

我有一个类的函数正在使用一个 promise (为简单起见,我正在使用 console.log()):

class Foo {

constructor() { }

async func(s) {
try {
await console.log(s)
} catch (e) {
console.error(e.message);
}
}
}

module.exports = { Foo };

当我调用 main.js 文件中的函数时,我想等到 promise 完成,然后执行下一步:

const {
Foo
} = require('./t22_1-async-await-class')

let foo = new Foo()

foo.func("1. Before Promise").then(() => {
console.log("2. Promise")
})


console.log("3. Later...");

但是,我得到:

1. Before Promise
3. Later...
2. Promise

我想执行 func() 然后才运行下一个 console.log()

我知道我可以使用 .then() 并将 console.log("3. Later..."); 包装在其中。如果我有很多代码想在那之后执行,这会变得非常困惑。

是否有另一种不使用 then() 来执行 func() 的方法?

感谢您的回复!

最佳答案

使用顶级等待(不是真正的等待,因为它仍然是 WD )


async function main(){
const {
Foo
} = require('./t22_1-async-await-class')
let foo = new Foo()

await foo.func("1. Before Promise")
console.log("2. Promise")
console.log("3. Later...");
}

关于javascript - 以单行方式从类运行异步/等待函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55970001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com