Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
async_op.hpp
Go to the documentation of this file.
1#pragma once
2
4#include <memory>
5#include <napi.h>
6#include <utility>
7
8namespace bb::nodejs {
9
10using async_fn = std::function<void(msgpack::sbuffer&)>;
11
27class AsyncOperation : public Napi::AsyncWorker {
28 public:
29 AsyncOperation(Napi::Env env, std::shared_ptr<Napi::Promise::Deferred> deferred, async_fn fn)
30 : Napi::AsyncWorker(env)
31 , _fn(std::move(fn))
32 , _deferred(std::move(deferred))
33 {}
34
39
40 ~AsyncOperation() override = default;
41
42 void Execute() override
43 {
44 try {
45 _fn(_result);
46 } catch (const std::exception& e) {
47 SetError(e.what());
48 } catch (...) {
49 // Catch any other exception type that's not derived from std::exception
50 // This ensures the promise is always rejected rather than leaving it hanging
51 SetError("Unknown exception occurred during async operation");
52 }
53 }
54
55 void OnOK() override
56 {
57 auto buf = Napi::Buffer<char>::Copy(Env(), _result.data(), _result.size());
58 _deferred->Resolve(buf);
59 }
60 void OnError(const Napi::Error& e) override { _deferred->Reject(e.Value()); }
61
62 private:
64 std::shared_ptr<Napi::Promise::Deferred> _deferred;
65 msgpack::sbuffer _result;
66};
67
68} // namespace bb::nodejs
Encapsulatest some work that can be done off the JavaScript main thread.
Definition async_op.hpp:27
AsyncOperation & operator=(AsyncOperation &&)=delete
void Execute() override
Definition async_op.hpp:42
AsyncOperation(AsyncOperation &&)=delete
AsyncOperation & operator=(const AsyncOperation &)=delete
AsyncOperation(const AsyncOperation &)=delete
~AsyncOperation() override=default
AsyncOperation(Napi::Env env, std::shared_ptr< Napi::Promise::Deferred > deferred, async_fn fn)
Definition async_op.hpp:29
void OnError(const Napi::Error &e) override
Definition async_op.hpp:60
std::shared_ptr< Napi::Promise::Deferred > _deferred
Definition async_op.hpp:64
msgpack::sbuffer _result
Definition async_op.hpp:65
uint8_t const * buf
Definition data_store.hpp:9
std::function< void(msgpack::sbuffer &)> async_fn
Definition async_op.hpp:10
STL namespace.