I've been questionning myself recently on how to reproduce a behaviour of then/catch with an async/await syntax.
With then/catch, I can define a callback which is only executed when the Promise resolves and then continue the execution like so .
function test() {
getUsersFromDB().then(users => console.log(users));
console.log('The rest of the code here continues to execute');
[...]
// Promise resolves and logs the users value
}
For me, with async/await you can have 2 possible behaviours.
1. Wait for the function and block the rest of the execution
async function test() {
const users = await getUsersFromDB();
// Code in here is not executed until promises returns
console.log(users);
}
2. Don't wait for the return value but don't expect you promise to be fulfilled when the rest of the code executes
function test() {
const users = getUsersFromDB();
// May log undefined
console.log(users);
}
Can I reproduce the first use case using async/await ?