LifeWanted / liblw

An asynchronous application framework built on C++ coroutines and epoll.
MIT License
39 stars 9 forks source link

Invalid promise behaviour #4

Open korrix opened 5 years ago

korrix commented 5 years ago

Future callback is not invoked if promise gets resolved before it was hooked:

Promise<int> p;
p.resolve(5);
p.future().then([](auto a) {
  std::cout << "a: " << a << std::endl; // does not print anything
});
NatalieWolfe commented 5 years ago

Thanks for looking at this old project! Unfortunately the behavior you identified was a conscious design choice at the time of implementation. I wanted to avoid causing unnecessary copying of the resolve value in the situation where the resolve handler is hooked already. This could probably be fixed at the same time as adding support for multiple resolve/reject handlers by making the shape of Promise::_SharedState polymorphic.

For example, creating the following structs _ResolvedSharedState, _RejectedSharedState, _MonoHandlerSharedState, _MultiHandlerSharedState. Then resolution would change to check if the shared state is either of the handler versions, execute those handlers, and replace the state with either _Resolved* or _Rejected*. Chaining (then, catch) would also need to be updated to check if the state is already resolved or rejected and act appropriately.