如何使用asnyc第三方库实现Node JS插件。 我能够实现同步函数,但是当谈到异步函数时,不确定它是如何工作的。它应该从主循环调用还是应该在async_work中。
该场景类似于http://nikhilm.github.io/uvbook/threads.html#inter-thread-communication中解释的示例,但我不想在async_work中下载,而是调用负责下载的异步函数。
示例异步功能:下载(url,回调);
示例代码:
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一直在等待回调。
非常感谢任何例子。
提前致谢。