3

如何使用 asnyc 第三方库实现 Node JS 插件。我能够实现同步函数,但是当涉及到异步函数时,我不确定它是如何工作的。它应该从主循环调用还是应该在 async_work 中。

该场景类似于http://nikhilm.github.io/uvbook/threads.html#inter-thread-communication中解释的示例,但不是在 async_work 中下载,而是我想调用负责下载的异步函数。

示例异步函数:下载(网址,回调);

示例代码:

Handle<Value> DNS::Download(const Arguments& args) {
    HandleScope scope;
    uv_loop_t *loop = uv_default_loop();
    uv_async_t *uv_async_req = new uv_async_t;
    uv_work_t *uv_work_req = new uv_work_t;

    AsyncData *asyncData = new AsyncData;
    asyncData->url = "http://..../";

    uv_async_req->data = asyncData;
    uv_work_req->data = asyncData;

    uv_async_init(loop, uv_async_req, send_progress);
    uv_queue_work(loop, uv_work_req, initiate_download, after);

    //Not sure if i have to invoke download(url, callback); here itself
    //or in fake_download

    return scope.Close(Undefined());
}

void send_progress(uv_async_t *handle, int status /*UNUSED*/) {
    AsyncData *asyncData = (AsyncData*)handle->data;
    Handle<Value> values[] = {};
    //Invoking js callback function.
    asyncData->callback->Call(Context::GetCurrent()->Global(), 0, values);
}

void initiate_download(uv_work_t *req) {
    //I would like to invoke non blocking async function here
    download(url, callback);
}

void callback(status, size) {
    //Send event to the send_progress
    uv_async_send(&async);
}

在这两种情况下(在主线程或 async_work 中调用)都没有调用我的回调,并且 JavaScript 一直在等待回调。

任何例子都非常感谢。

提前致谢。

4

0 回答 0