how to avoid callback hell with boost::beast?

1k Views Asked by At

I'm working on an application in which I want to use boost::beast/asio. I need to receive data via a websocket connection and issue requests to a REST API at the same time.

In the boost::beast websocket/HTTP async client examples it seems like the next async operation is started in the completion handlers. This seems to give rise to the same "callback hell" I've seen in node.js applications.

To avoid this I'm thinking of using a simple state machine in my application to decide what operation to start next. I'm thinking of having a while loop in my application where I call poll() on the io_context after which I run my state machine code (e.g. switch(state) { ... state = nextState; } )

However this might create a busy loop in which the main thread consumes 100% cpu while it constantly runs the state machine?

Is my reasoning correct and would it be better to use something like post() to queue a functor which would advance the state machine?

1

There are 1 best solutions below

2
On

I wish I could leave this as a comment since it's not really a full answer, but I don't have enough reputation to comment.

If you're talking about node.js, I assume you have some experience with 'promises' and/or the newer 'async/await' - at least that's how node.js avoids callback hell.

Turns out Boost Asio has something similar to node.js 'async/await'. It's called Boost Asio Coroutines and you implement it the exact same way as node.js 'async/await'.

Not sure if it's a good idea to run a while loop which consumes 100% of the thread? That's a bit of a waste when there are better solutions.