Reputation: 1454
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 ?
Upvotes: 1
Views: 1783
Reputation: 298
So what you need is basically split the code. One piece should be executed in async/await syntax, and another one should be as usual.
First what I want to say, if you do as follows
async function test() {
console.log('The rest of the code here continues to execute');
const users = await getUsersFromDB();
// Code in here is not executed until promises returns
console.log(users);
}
that will do the trick. This may appear a little strange because we just moved the line a bit up, this is not what we wanted to do, but...
The await
keyword stops execution of an async
function, but we have some code that should continue working at the time when await
freezes the function, that means we can't place the code after await
, only before.
As far as I understand, the code tahat is indicated as "The rest of the code here continues to execute" can be asynchronous too, so the resulting example will be as follows:
async function test() {
console.log('Some synchronous code');
setImmediate(() => {
console.log('Some asynchronous code');
});
const users = await getUsersFromDB();
// Code in here is not executed until promises returns
console.log(users);
}
Upvotes: 0
Reputation: 664548
Using then
is the simplest solution, but you can use an AIIFE:
function test() {
(async () => {
const users = await getUsersFromDB();
console.log(users);
})().catch(console.error);
console.log('The rest of the code here continues to execute');
[...]
// Promise resolves and logs the users value
}
An alternative could only be async do
expressions.
Upvotes: 1