1# AsyncProgressWorker 2 3`Napi::AsyncProgressWorker` is an abstract class which implements `Napi::AsyncWorker` 4while extending `Napi::AsyncWorker` internally with `Napi::ThreadSafeFunction` for 5moving work progress reports from worker thread(s) to event loop threads. 6 7Like `Napi::AsyncWorker`, once created, execution is requested by calling 8`Napi::AsyncProgressWorker::Queue`. When a thread is available for execution 9the `Napi::AsyncProgressWorker::Execute` method will be invoked. During the 10execution, `Napi::AsyncProgressWorker::ExecutionProgress::Send` can be used to 11indicate execution process, which will eventually invoke `Napi::AsyncProgressWorker::OnProgress` 12on the JavaScript thread to safely call into JavaScript. Once `Napi::AsyncProgressWorker::Execute` 13completes either `Napi::AsyncProgressWorker::OnOK` or `Napi::AsyncProgressWorker::OnError` 14will be invoked. Once the `Napi::AsyncProgressWorker::OnOK` or `Napi::AsyncProgressWorker::OnError` 15methods are complete the `Napi::AsyncProgressWorker` instance is destructed. 16 17For the most basic use, only the `Napi::AsyncProgressWorker::Execute` and 18`Napi::AsyncProgressWorker::OnProgress` method must be implemented in a subclass. 19 20## Methods 21 22[`Napi::AsyncWorker`][] provides detailed descriptions for most methods. 23 24### Execute 25 26This method is used to execute some tasks outside of the **event loop** on a libuv 27worker thread. Subclasses must implement this method and the method is run on 28a thread other than that running the main event loop. As the method is not 29running on the main event loop, it must avoid calling any methods from node-addon-api 30or running any code that might invoke JavaScript. Instead, once this method is 31complete any interaction through node-addon-api with JavaScript should be implemented 32in the `Napi::AsyncProgressWorker::OnOK` method and/or `Napi::AsyncProgressWorker::OnError` 33which run on the main thread and are invoked when the `Napi::AsyncProgressWorker::Execute` 34method completes. 35 36```cpp 37virtual void Napi::AsyncProgressWorker::Execute(const ExecutionProgress& progress) = 0; 38``` 39 40### OnOK 41 42This method is invoked when the computation in the `Execute` method ends. 43The default implementation runs the `Callback` optionally provided when the 44`AsyncProgressWorker` class was created. The `Callback` will by default receive no 45arguments. Arguments to the callback can be provided by overriding the `GetResult()` 46method. 47 48```cpp 49virtual void Napi::AsyncProgressWorker::OnOK(); 50``` 51 52### OnProgress 53 54This method is invoked when the computation in the 55`Napi::AsyncProgressWorker::ExecutionProgress::Send` method was called during 56worker thread execution. This method can also be triggered via a call to 57`Napi::AsyncProgress[Queue]Worker::ExecutionProgress::Signal`, in which case the 58`data` parameter will be `nullptr`. 59 60```cpp 61virtual void Napi::AsyncProgressWorker::OnProgress(const T* data, size_t count) 62``` 63 64### Constructor 65 66Creates a new `Napi::AsyncProgressWorker`. 67 68```cpp 69explicit Napi::AsyncProgressWorker(const Napi::Function& callback); 70``` 71 72- `[in] callback`: The function which will be called when an asynchronous 73operations ends. The given function is called from the main event loop thread. 74 75Returns a `Napi::AsyncProgressWorker` instance which can later be queued for execution by 76calling `Napi::AsyncWork::Queue`. 77 78### Constructor 79 80Creates a new `Napi::AsyncProgressWorker`. 81 82```cpp 83explicit Napi::AsyncProgressWorker(const Napi::Function& callback, const char* resource_name); 84``` 85 86- `[in] callback`: The function which will be called when an asynchronous 87operations ends. The given function is called from the main event loop thread. 88- `[in] resource_name`: Null-terminated string that represents the 89identifier for the kind of resource that is being provided for diagnostic 90information exposed by the async_hooks API. 91 92Returns a `Napi::AsyncProgressWorker` instance which can later be queued for execution by 93calling `Napi::AsyncWork::Queue`. 94 95### Constructor 96 97Creates a new `Napi::AsyncProgressWorker`. 98 99```cpp 100explicit Napi::AsyncProgressWorker(const Napi::Function& callback, const char* resource_name, const Napi::Object& resource); 101``` 102 103- `[in] callback`: The function which will be called when an asynchronous 104operations ends. The given function is called from the main event loop thread. 105- `[in] resource_name`: Null-terminated string that represents the 106identifier for the kind of resource that is being provided for diagnostic 107information exposed by the async_hooks API. 108- `[in] resource`: Object associated with the asynchronous operation that 109will be passed to possible async_hooks. 110 111Returns a `Napi::AsyncProgressWorker` instance which can later be queued for execution by 112calling `Napi::AsyncWork::Queue`. 113 114### Constructor 115 116Creates a new `Napi::AsyncProgressWorker`. 117 118```cpp 119explicit Napi::AsyncProgressWorker(const Napi::Object& receiver, const Napi::Function& callback); 120``` 121 122- `[in] receiver`: The `this` object passed to the called function. 123- `[in] callback`: The function which will be called when an asynchronous 124operations ends. The given function is called from the main event loop thread. 125 126Returns a `Napi::AsyncProgressWorker` instance which can later be queued for execution by 127calling `Napi::AsyncWork::Queue`. 128 129### Constructor 130 131Creates a new `Napi::AsyncProgressWorker`. 132 133```cpp 134explicit Napi::AsyncProgressWorker(const Napi::Object& receiver, const Napi::Function& callback, const char* resource_name); 135``` 136 137- `[in] receiver`: The `this` object passed to the called function. 138- `[in] callback`: The function which will be called when an asynchronous 139operations ends. The given function is called from the main event loop thread. 140- `[in] resource_name`: Null-terminated string that represents the 141identifier for the kind of resource that is being provided for diagnostic 142information exposed by the async_hooks API. 143 144Returns a `Napi::AsyncWork` instance which can later be queued for execution by 145calling `Napi::AsyncWork::Queue`. 146 147### Constructor 148 149Creates a new `Napi::AsyncProgressWorker`. 150 151```cpp 152explicit Napi::AsyncProgressWorker(const Napi::Object& receiver, const Napi::Function& callback, const char* resource_name, const Napi::Object& resource); 153``` 154 155- `[in] receiver`: The `this` object to be passed to the called function. 156- `[in] callback`: The function which will be called when an asynchronous 157operations ends. The given function is called from the main event loop thread. 158- `[in] resource_name`: Null-terminated string that represents the 159identifier for the kind of resource that is being provided for diagnostic 160information exposed by the async_hooks API. 161- `[in] resource`: Object associated with the asynchronous operation that 162will be passed to possible async_hooks. 163 164Returns a `Napi::AsyncWork` instance which can later be queued for execution by 165calling `Napi::AsyncWork::Queue`. 166 167### Constructor 168 169Creates a new `Napi::AsyncProgressWorker`. 170 171```cpp 172explicit Napi::AsyncProgressWorker(Napi::Env env); 173``` 174 175- `[in] env`: The environment in which to create the `Napi::AsyncProgressWorker`. 176 177Returns an `Napi::AsyncProgressWorker` instance which can later be queued for execution by calling 178`Napi::AsyncProgressWorker::Queue`. 179 180Available with `NAPI_VERSION` equal to or greater than 5. 181 182### Constructor 183 184Creates a new `Napi::AsyncProgressWorker`. 185 186```cpp 187explicit Napi::AsyncProgressWorker(Napi::Env env, const char* resource_name); 188``` 189 190- `[in] env`: The environment in which to create the `Napi::AsyncProgressWorker`. 191- `[in] resource_name`: Null-terminated string that represents the 192identifier for the kind of resource that is being provided for diagnostic 193information exposed by the async_hooks API. 194 195Returns a `Napi::AsyncProgressWorker` instance which can later be queued for execution by 196calling `Napi::AsyncProgressWorker::Queue`. 197 198Available with `NAPI_VERSION` equal to or greater than 5. 199 200### Constructor 201 202Creates a new `Napi::AsyncProgressWorker`. 203 204```cpp 205explicit Napi::AsyncProgressWorker(Napi::Env env, const char* resource_name, const Napi::Object& resource); 206``` 207 208- `[in] env`: The environment in which to create the `Napi::AsyncProgressWorker`. 209- `[in] resource_name`: Null-terminated string that represents the 210identifier for the kind of resource that is being provided for diagnostic 211information exposed by the async_hooks API. 212- `[in] resource`: Object associated with the asynchronous operation that 213will be passed to possible async_hooks. 214 215Returns a `Napi::AsyncProgressWorker` instance which can later be queued for execution by 216calling `Napi::AsyncProgressWorker::Queue`. 217 218Available with `NAPI_VERSION` equal to or greater than 5. 219 220### Destructor 221 222Deletes the created work object that is used to execute logic asynchronously and 223release the internal `Napi::ThreadSafeFunction`, which will be aborted to prevent 224unexpected upcoming thread safe calls. 225 226```cpp 227virtual Napi::AsyncProgressWorker::~AsyncProgressWorker(); 228``` 229 230# AsyncProgressWorker::ExecutionProgress 231 232A bridge class created before the worker thread execution of `Napi::AsyncProgressWorker::Execute`. 233 234## Methods 235 236### Send 237 238`Napi::AsyncProgressWorker::ExecutionProgress::Send` takes two arguments, a pointer 239to a generic type of data, and a `size_t` to indicate how many items the pointer is 240pointing to. 241 242The data pointed to will be copied to internal slots of `Napi::AsyncProgressWorker` so 243after the call to `Napi::AsyncProgressWorker::ExecutionProgress::Send` the data can 244be safely released. 245 246Note that `Napi::AsyncProgressWorker::ExecutionProgress::Send` merely guarantees 247**eventual** invocation of `Napi::AsyncProgressWorker::OnProgress`, which means 248multiple send might be coalesced into single invocation of `Napi::AsyncProgressWorker::OnProgress` 249with latest data. If you would like to guarantee that there is one invocation of 250`OnProgress` for every `Send` call, you should use the `Napi::AsyncProgressQueueWorker` 251class instead which is documented further down this page. 252 253```cpp 254void Napi::AsyncProgressWorker::ExecutionProgress::Send(const T* data, size_t count) const; 255``` 256 257### Signal 258 259`Napi::AsyncProgressWorker::ExecutionProgress::Signal` triggers an invocation of 260`Napi::AsyncProgressWorker::OnProgress` with `nullptr` as the `data` parameter. 261 262```cpp 263void Napi::AsyncProgressWorker::ExecutionProgress::Signal(); 264``` 265 266## Example 267 268The first step to use the `Napi::AsyncProgressWorker` class is to create a new class that 269inherits from it and implement the `Napi::AsyncProgressWorker::Execute` abstract method. 270Typically input to the worker will be saved within the class' fields generally 271passed in through its constructor. 272 273During the worker thread execution, the first argument of `Napi::AsyncProgressWorker::Execute` 274can be used to report the progress of the execution. 275 276When the `Napi::AsyncProgressWorker::Execute` method completes without errors the 277`Napi::AsyncProgressWorker::OnOK` function callback will be invoked. In this function the 278results of the computation will be reassembled and returned back to the initial 279JavaScript context. 280 281`Napi::AsyncProgressWorker` ensures that all the code in the `Napi::AsyncProgressWorker::Execute` 282function runs in the background out of the **event loop** thread and at the end 283the `Napi::AsyncProgressWorker::OnOK` or `Napi::AsyncProgressWorker::OnError` function will be 284called and are executed as part of the event loop. 285 286The code below shows a basic example of the `Napi::AsyncProgressWorker` implementation along with an 287example of how the counterpart in Javascript would appear: 288 289```cpp 290#include <napi.h> 291 292#include <chrono> 293#include <thread> 294 295using namespace Napi; 296 297class EchoWorker : public AsyncProgressWorker<uint32_t> { 298 public: 299 EchoWorker(Function& okCallback, std::string& echo) 300 : AsyncProgressWorker(okCallback), echo(echo) {} 301 302 ~EchoWorker() {} 303 304 // This code will be executed on the worker thread 305 void Execute(const ExecutionProgress& progress) { 306 // Need to simulate cpu heavy task 307 // Note: This Send() call is not guaranteed to trigger an equal 308 // number of OnProgress calls (read documentation above for more info) 309 for (uint32_t i = 0; i < 100; ++i) { 310 progress.Send(&i, 1) 311 } 312 } 313 314 void OnError(const Error &e) { 315 HandleScope scope(Env()); 316 // Pass error onto JS, no data for other parameters 317 Callback().Call({String::New(Env(), e.Message())}); 318 } 319 320 void OnOK() { 321 HandleScope scope(Env()); 322 // Pass no error, give back original data 323 Callback().Call({Env().Null(), String::New(Env(), echo)}); 324 } 325 326 void OnProgress(const uint32_t* data, size_t /* count */) { 327 HandleScope scope(Env()); 328 // Pass no error, no echo data, but do pass on the progress data 329 Callback().Call({Env().Null(), Env().Null(), Number::New(Env(), *data)}); 330 } 331 332 private: 333 std::string echo; 334}; 335``` 336 337The `EchoWorker`'s constructor calls the base class' constructor to pass in the 338callback that the `Napi::AsyncProgressWorker` base class will store persistently. When 339the work on the `Napi::AsyncProgressWorker::Execute` method is done the 340`Napi::AsyncProgressWorker::OnOk` method is called and the results are return back to 341JavaScript when the stored callback is invoked with its associated environment. 342 343The following code shows an example of how to create and use an `Napi::AsyncProgressWorker` 344 345```cpp 346#include <napi.h> 347 348// Include EchoWorker class 349// .. 350 351using namespace Napi; 352 353Value Echo(const CallbackInfo& info) { 354 // We need to validate the arguments here 355 std::string in = info[0].As<String>(); 356 Function cb = info[1].As<Function>(); 357 EchoWorker* wk = new EchoWorker(cb, in); 358 wk->Queue(); 359 return info.Env().Undefined(); 360} 361 362// Register the native method for JS to access 363Object Init(Env env, Object exports) 364{ 365 exports.Set(String::New(env, "echo"), Function::New(env, Echo)); 366 367 return exports; 368} 369 370// Register our native addon 371NODE_API_MODULE(nativeAddon, Init) 372``` 373 374The implementation of a `Napi::AsyncProgressWorker` can be used by creating a 375new instance and passing to its constructor the callback to execute when the 376asynchronous task ends and other data needed for the computation. Once created, 377the only other action needed is to call the `Napi::AsyncProgressWorker::Queue` 378method that will queue the created worker for execution. 379 380Lastly, the following Javascript (ES6+) code would be associated the above example: 381 382```js 383const { nativeAddon } = require('binding.node'); 384 385const exampleCallback = (errorResponse, okResponse, progressData) => { 386 // Use the data accordingly 387 // ... 388}; 389 390// Call our native addon with the parameters of a string and a function 391nativeAddon.echo("example", exampleCallback); 392``` 393 394# AsyncProgressQueueWorker 395 396`Napi::AsyncProgressQueueWorker` acts exactly like `Napi::AsyncProgressWorker` 397except that each progress committed by `Napi::AsyncProgressQueueWorker::ExecutionProgress::Send` 398during `Napi::AsyncProgressQueueWorker::Execute` is guaranteed to be 399processed by `Napi::AsyncProgressQueueWorker::OnProgress` on the JavaScript 400thread in the order it was committed. 401 402For the most basic use, only the `Napi::AsyncProgressQueueWorker::Execute` and 403`Napi::AsyncProgressQueueWorker::OnProgress` method must be implemented in a subclass. 404 405# AsyncProgressQueueWorker::ExecutionProgress 406 407A bridge class created before the worker thread execution of `Napi::AsyncProgressQueueWorker::Execute`. 408 409## Methods 410 411### Send 412 413`Napi::AsyncProgressQueueWorker::ExecutionProgress::Send` takes two arguments, a pointer 414to a generic type of data, and a `size_t` to indicate how many items the pointer is 415pointing to. 416 417The data pointed to will be copied to internal slots of `Napi::AsyncProgressQueueWorker` so 418after the call to `Napi::AsyncProgressQueueWorker::ExecutionProgress::Send` the data can 419be safely released. 420 421`Napi::AsyncProgressQueueWorker::ExecutionProgress::Send` guarantees invocation 422of `Napi::AsyncProgressQueueWorker::OnProgress`, which means multiple `Send` 423call will result in the in-order invocation of `Napi::AsyncProgressQueueWorker::OnProgress` 424with each data item. 425 426```cpp 427void Napi::AsyncProgressQueueWorker::ExecutionProgress::Send(const T* data, size_t count) const; 428``` 429 430### Signal 431 432`Napi::AsyncProgressQueueWorker::ExecutionProgress::Signal` triggers an invocation of 433`Napi::AsyncProgressQueueWorker::OnProgress` with `nullptr` as the `data` parameter. 434 435```cpp 436void Napi::AsyncProgressQueueWorker::ExecutionProgress::Signal() const; 437``` 438 439## Example 440 441The code below shows an example of the `Napi::AsyncProgressQueueWorker` implementation, but 442also demonstrates how to use multiple `Napi::Function`'s if you wish to provide multiple 443callback functions for more object-oriented code: 444 445```cpp 446#include <napi.h> 447 448#include <chrono> 449#include <thread> 450 451using namespace Napi; 452 453class EchoWorker : public AsyncProgressQueueWorker<uint32_t> { 454 public: 455 EchoWorker(Function& okCallback, Function& errorCallback, Function& progressCallback, std::string& echo) 456 : AsyncProgressQueueWorker(okCallback), echo(echo) { 457 // Set our function references to use them below 458 this->errorCallback.Reset(errorCallback, 1); 459 this->progressCallback.Reset(progressCallback, 1); 460 } 461 462 ~EchoWorker() {} 463 464 // This code will be executed on the worker thread 465 void Execute(const ExecutionProgress& progress) { 466 // Need to simulate cpu heavy task to demonstrate that 467 // every call to Send() will trigger an OnProgress function call 468 for (uint32_t i = 0; i < 100; ++i) { 469 progress.Send(&i, 1); 470 } 471 } 472 473 void OnOK() { 474 HandleScope scope(Env()); 475 // Call our onOkCallback in javascript with the data we were given originally 476 Callback().Call({String::New(Env(), echo)}); 477 } 478 479 void OnError(const Error &e) { 480 HandleScope scope(Env()); 481 482 // We call our callback provided in the constructor with 2 parameters 483 if (!this->errorCallback.IsEmpty()) { 484 // Call our onErrorCallback in javascript with the error message 485 this->errorCallback.Call(Receiver().Value(), {String::New(Env(), e.Message())}); 486 } 487 } 488 489 void OnProgress(const uint32_t* data, size_t /* count */) { 490 HandleScope scope(Env()); 491 492 if (!this->progressCallback.IsEmpty()) { 493 // Call our onProgressCallback in javascript with each integer from 0 to 99 (inclusive) 494 // as this function is triggered from the above Send() calls 495 this->progressCallback.Call(Receiver().Value(), {Number::New(Env(), *data)}); 496 } 497 } 498 499 private: 500 std::string echo; 501 FunctionReference progressCallback; 502 FunctionReference errorCallback; 503 504}; 505``` 506 507The `EchoWorker`'s constructor calls the base class' constructor to pass in the 508callback that the `Napi::AsyncProgressQueueWorker` base class will store 509persistently. When the work on the `Napi::AsyncProgressQueueWorker::Execute` 510method is done the `Napi::AsyncProgressQueueWorker::OnOk` method is called and 511the results are returned back to JavaScript when the stored callback is invoked 512with its associated environment. 513 514The following code shows an example of how to create and use an 515`Napi::AsyncProgressQueueWorker`. 516 517```cpp 518#include <napi.h> 519 520// Include EchoWorker class 521// .. 522 523using namespace Napi; 524 525Value Echo(const CallbackInfo& info) { 526 // We need to validate the arguments here. 527 std::string in = info[0].As<String>(); 528 Function errorCb = info[1].As<Function>(); 529 Function okCb = info[2].As<Function>(); 530 Function progressCb = info[3].As<Function>(); 531 EchoWorker* wk = new EchoWorker(okCb, errorCb, progressCb, in); 532 wk->Queue(); 533 return info.Env().Undefined(); 534} 535 536// Register the native method for JS to access 537Object Init(Env env, Object exports) 538{ 539 exports.Set(String::New(env, "echo"), Function::New(env, Echo)); 540 541 return exports; 542} 543 544// Register our native addon 545NODE_API_MODULE(nativeAddon, Init) 546``` 547 548The implementation of a `Napi::AsyncProgressQueueWorker` can be used by creating a 549new instance and passing to its constructor the callback to execute when the 550asynchronous task ends and other data needed for the computation. Once created, 551the only other action needed is to call the `Napi::AsyncProgressQueueWorker::Queue` 552method that will queue the created worker for execution. 553 554Lastly, the following Javascript (ES6+) code would be associated the above example: 555 556```js 557const { nativeAddon } = require('binding.node'); 558 559const onErrorCallback = (msg) => { 560 // Use the data accordingly 561 // ... 562}; 563 564const onOkCallback = (echo) => { 565 // Use the data accordingly 566 // ... 567}; 568 569const onProgressCallback = (num) => { 570 // Use the data accordingly 571 // ... 572}; 573 574// Call our native addon with the parameters of a string and three callback functions 575nativeAddon.echo("example", onErrorCallback, onOkCallback, onProgressCallback); 576``` 577 578[`Napi::AsyncWorker`]: ./async_worker.md 579