MCPcopy Create free account
hub / github.com/nodejs/node-addon-api / CancelWorker

Class CancelWorker

test/async_worker.cc:273–320  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

271};
272
273class CancelWorker : public AsyncWorker {
274 public:
275 CancelWorker(Function& cb) : AsyncWorker(cb) {}
276 ~CancelWorker() {}
277
278 static void DoWork(const CallbackInfo& info) {
279 Function cb = info[0].As<Function>();
280 std::string echo = info[1].As<String>();
281 int threadNum = info[2].As<Number>().Uint32Value();
282
283 for (int i = 0; i < threadNum; i++) {
284 AsyncWorker* worker = new EchoWorker(cb, echo);
285 worker->Queue();
286 assert(worker->Env() == info.Env());
287 }
288
289 AsyncWorker* cancelWorker = new CancelWorker(cb);
290 cancelWorker->Queue();
291
292#ifdef NAPI_CPP_EXCEPTIONS
293 try {
294 cancelWorker->Cancel();
295 } catch (Napi::Error&) {
296 Napi::Error::New(info.Env(), "Unable to cancel async worker tasks")
297 .ThrowAsJavaScriptException();
298 }
299#else
300 cancelWorker->Cancel();
301#endif
302 }
303
304 void Execute() override {
305 // Simulate cpu heavy task
306 std::this_thread::sleep_for(std::chrono::milliseconds(100));
307 }
308
309 void OnOK() override {
310 Napi::Error::New(this->Env(),
311 "OnOk should not be invoked on successful cancellation")
312 .ThrowAsJavaScriptException();
313 }
314
315 void OnError(const Error&) override {
316 Napi::Error::New(this->Env(),
317 "OnError should not be invoked on successful cancellation")
318 .ThrowAsJavaScriptException();
319 }
320};
321
322Object InitAsyncWorker(Env env) {
323 Object exports = Object::New(env);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected