|
| 1 | +#include "hello_async.hpp" |
| 2 | + |
| 3 | +#include <exception> |
| 4 | +#include <stdexcept> |
| 5 | +#include <iostream> |
| 6 | +#include <map> |
| 7 | + |
| 8 | +namespace standalone_async { |
| 9 | + |
| 10 | + /* |
| 11 | + * This is an internal function used to return callback error messages instead of |
| 12 | + * throwing errors. |
| 13 | + * Usage: |
| 14 | + * |
| 15 | + * v8::Local<v8::Function> callback; |
| 16 | + * CallbackError("error message", callback); |
| 17 | + * return; // this is important to prevent duplicate callbacks from being fired! |
| 18 | + */ |
| 19 | + inline void CallbackError(std::string message, v8::Local<v8::Function> callback) { |
| 20 | + v8::Local<v8::Value> argv[1] = { Nan::Error(message.c_str()) }; |
| 21 | + Nan::MakeCallback(Nan::GetCurrentContext()->Global(), callback, 1, argv); |
| 22 | + } |
| 23 | + |
| 24 | + // Expensive allocation of std::map, querying, and string comparison, |
| 25 | + // therefore threads are busy |
| 26 | + std::string do_expensive_work(bool louder) { |
| 27 | + |
| 28 | + std::map<std::size_t,std::string> container; |
| 29 | + std::size_t work_to_do=100000; |
| 30 | + |
| 31 | + for (std::size_t i=0;i<work_to_do;++i) { |
| 32 | + container.emplace(i,std::to_string(i)); |
| 33 | + } |
| 34 | + |
| 35 | + for (std::size_t i=0;i<work_to_do;++i) { |
| 36 | + std::string const& item = container[i]; |
| 37 | + if (item != std::to_string(i)) { |
| 38 | + |
| 39 | + // AsyncHelloWorker's Execute function will take care of this error |
| 40 | + // and return it to js-world via callback |
| 41 | + throw std::runtime_error("Uh oh, this should never happen"); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + std::string result = "...threads are busy async bees...world"; |
| 46 | + |
| 47 | + if (louder) |
| 48 | + { |
| 49 | + result += "!!!!"; |
| 50 | + } |
| 51 | + |
| 52 | + return result; |
| 53 | + |
| 54 | + } |
| 55 | + |
| 56 | + // This is the worker running asynchronously and calling a user-provided callback when done. |
| 57 | + // Consider storing all C++ objects you need by value or by shared_ptr to keep them alive until done. |
| 58 | + // Nan AsyncWorker docs: https://github.com/nodejs/nan/blob/master/doc/asyncworker.md |
| 59 | + struct AsyncHelloWorker : Nan::AsyncWorker { |
| 60 | + using Base = Nan::AsyncWorker; |
| 61 | + |
| 62 | + AsyncHelloWorker(bool louder, Nan::Callback* callback) |
| 63 | + : Base(callback), result_{""}, louder_{louder} { } |
| 64 | + |
| 65 | + // The Execute() function is getting called when the worker starts to run. |
| 66 | + // - You only have access to member variables stored in this worker. |
| 67 | + // - You do not have access to Javascript v8 objects here. |
| 68 | + void Execute() override { |
| 69 | + try { |
| 70 | + result_ = do_expensive_work(louder_); |
| 71 | + } catch (const std::exception& e) { |
| 72 | + SetErrorMessage(e.what()); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + // The HandleOKCallback() is getting called when Execute() successfully completed. |
| 77 | + // - In case Execute() invoked SetErrorMessage("") this function is not getting called. |
| 78 | + // - You have access to Javascript v8 objects again |
| 79 | + // - You have to translate from C++ member variables to Javascript v8 objects |
| 80 | + // - Finally, you call the user's callback with your results |
| 81 | + void HandleOKCallback() override { |
| 82 | + Nan::HandleScope scope; |
| 83 | + |
| 84 | + const auto argc = 2u; |
| 85 | + v8::Local<v8::Value> argv[argc] = {Nan::Null(), Nan::New<v8::String>(result_).ToLocalChecked()}; |
| 86 | + |
| 87 | + callback->Call(argc, argv); |
| 88 | + } |
| 89 | + |
| 90 | + std::string result_; |
| 91 | + const bool louder_; |
| 92 | + }; |
| 93 | + |
| 94 | + // hello_async is a "standalone function" because it's not a class. |
| 95 | + // If this function was not defined within a namespace ("standalone_async"), it would be in the global scope. |
| 96 | + NAN_METHOD(hello_async) { |
| 97 | + |
| 98 | + bool louder = false; |
| 99 | + |
| 100 | + // Check second argument, should be a 'callback' function. |
| 101 | + // This allows us to set the callback so we can use it to return errors instead of throwing. |
| 102 | + // Also, "info" comes from the NAN_METHOD macro, which returns differently according to the version of node |
| 103 | + if (!info[1]->IsFunction()) |
| 104 | + { |
| 105 | + return Nan::ThrowTypeError("second arg 'callback' must be a function"); |
| 106 | + } |
| 107 | + v8::Local<v8::Function> callback = info[1].As<v8::Function>(); |
| 108 | + |
| 109 | + // Check first argument, should be an 'options' object |
| 110 | + if (!info[0]->IsObject()) |
| 111 | + { |
| 112 | + return CallbackError("first arg 'options' must be an object", callback); |
| 113 | + } |
| 114 | + v8::Local<v8::Object> options = info[0].As<v8::Object>(); |
| 115 | + |
| 116 | + // Check options object for the "louder" property, which should be a boolean value |
| 117 | + if (options->Has(Nan::New("louder").ToLocalChecked())) |
| 118 | + { |
| 119 | + v8::Local<v8::Value> louder_val = options->Get(Nan::New("louder").ToLocalChecked()); |
| 120 | + if (!louder_val->IsBoolean()) |
| 121 | + { |
| 122 | + return CallbackError("option 'louder' must be a boolean", callback); |
| 123 | + } |
| 124 | + louder = louder_val->BooleanValue(); |
| 125 | + } |
| 126 | + |
| 127 | + // Create a worker instance and queues it to run asynchronously invoking the callback when done. |
| 128 | + // - Nan::AsyncWorker takes a pointer to a Nan::Callback and deletes the pointer automatically. |
| 129 | + // - Nan::AsyncQueueWorker takes a pointer to a Nan::AsyncWorker and deletes the pointer automatically. |
| 130 | + auto* worker = new AsyncHelloWorker{louder, new Nan::Callback{callback}}; |
| 131 | + Nan::AsyncQueueWorker(worker); |
| 132 | + |
| 133 | + } |
| 134 | + |
| 135 | +} // namespace standalone_async |
| 136 | + |
| 137 | + |
0 commit comments