Skip to content
Advertisement

How to log return value after async/await?

Below have I pasted in PoC code, where I have removed lots of lines, but it shows the problem/question I am facing.

createPost() returns a “post number” in the ret variable. I don’t need the “post number for anything else than logging it.

With the current implementation, I have to define ret outside of the while loop, and since sequential code is run before asynchronous code in the NodeJS event loop, I expect the logging will be executed before createPost(), which is not what I want.

Question

Is it possible to only log ret when createPost() have been executed?

JavaScript

createPost.js

JavaScript

Advertisement

Answer

…and since sequential code is run before asynchronous code in the NodeJS event loop, I expect the logging will be executed before createPost(), which is not what I want.

All of the code in an async function after the first await is asynchronous, not synchronous. In your code, the appLogger.info call won’t happen until createPost has finished its work (asynchronously).

So there’s no need to declare ret outside the loop (and even if the above weren’t true, that wouldn’t really help), you can just do it inline, see *** comments:

JavaScript

The code waits, asynchronously, at the await and only continues when createPost is done.

Here’s a simplified example:

JavaScript

Technically, you don’t need ret at all, this would also work:

JavaScript

but if it were me, I’d keep it as shown in the first code block above. It’s easier to debug.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement