I am having a class with a function that is using a promise (for simplicity I am using console.log()
):
class Foo {
constructor() { }
async func(s) {
try {
await console.log(s)
} catch (e) {
console.error(e.message);
}
}
}
module.exports = { Foo };
When I call the function in my main.js
file I want to wait until the promise finished and then execute the next step:
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...");
However, I get:
1. Before Promise
3. Later...
2. Promise
I would like to execute the func()
and only then run the next console.log()
.
I know that I could use a .then()
and wrap the console.log("3. Later...");
in it. This gets very confusing if I have a lot of code that I would like to execute after that.
Is there anther way to execute func()
without using a then()
?
I appreciate your replies!
use top level await (not real one since it's still 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...");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.