#鸿蒙通关秘籍#如何使用Node-API创建异步任务以避免阻塞主线程?

HarmonyOS
8h前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
ScriptScribe

通过Node-API进行异步任务的创建和管理,可以有效避免阻塞主线程。在Node-API中,可以使用napi_create_async_work函数来创建异步任务,然后使用napi_queue_async_work将其加入到队列中,从而提高应用程序的响应性能。以下是一个完整的示例代码,展示如何创建一个异步任务并使用Promise方式处理结果:

cpp struct CallbackData { napi_async_work asyncWork = nullptr; napi_deferred deferred = nullptr; napi_ref callback = nullptr; double args = 0; double result = 0; };

static napi_value AsyncWork(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);

napi_value promise = nullptr; napi_deferred deferred = nullptr; napi_create_promise(env, &deferred, &promise);

auto callbackData = new CallbackData(); callbackData->deferred = deferred; napi_get_value_double(env, args[0], &callbackData->args);

napi_value resourceName = nullptr; napi_create_string_utf8(env, "AsyncCallback", NAPI_AUTO_LENGTH, &resourceName); napi_create_async_work(env, nullptr, resourceName, ExecuteCB, CompleteCB, callbackData, &callbackData->asyncWork); napi_queue_async_work(env, callbackData->asyncWork);

return promise; }

static void ExecuteCB(napi_env env, void *data) { CallbackData *callbackData = reinterpret_cast<CallbackData *>(data); callbackData->result = callbackData->args; }

static void CompleteCB(napi_env env, napi_status status, void *data) { CallbackData *callbackData = reinterpret_cast<CallbackData *>(data); napi_value result = nullptr; napi_create_double(env, callbackData->result, &result); if (callbackData->result > 0) { napi_resolve_deferred(env, callbackData->deferred, result); } else { napi_reject_deferred(env, callbackData->deferred, result); }

napi_delete_async_work(env, callbackData->asyncWork);
delete callbackData;

}

static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { { "asyncWork", nullptr, AsyncWork, nullptr, nullptr, nullptr, napi_default, nullptr } }; napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); return exports; }

nativeModule.asyncWork(1024).then((result) => { hilog.info(0x0000, 'XXX', 'result is %{public}d', result); });

分享
微博
QQ
微信
回复
7h前
相关问题