How to use Node Worker in Wakanda

108 views Asked by At

Up until now for me the concept of a Node Worker has been one of those things that sounds interesting and I will find out about one day.

Well that day has come and I am asking for some help.

I need to call a web service and then process the data returned. I can call the service with an XMLHttpRequest, but then I have to get useful data out of it.

There is a nice node module that both calls the service and returns the data in a useful form with one call.

I can set up Node worker (in Wakanda) to do this and verify that it works.

My problem is handling the asynchronous call in the proxy.

The call to the node module looks like this:

myModule.getData(param, (err, data) => {
  // data is an object containing everything I want.
  // if I get data I want to return it to the proxy
  // if I get an err I want to return the error to the proxy
});

So my wrapper code looks something like this:

function doSomething(param){

  // call proxy with param
  // wait for result
  //  return result
  
}

This all sounds like something I should know how to do. However I think I am struggling with too many new things and getting myself absolutely confused.

PS: I did try Threadify but couldn't work out how to get the worker to return the error it received.

I would really appreciate any help or pointers here.

1

There are 1 answers

1
Jeff G On BEST ANSWER

If I am correctly understanding your issue, you cannot return a value from a function AFTER an asynchronous call completes. You need to handle the data within the myModule.getData callback.

If you would rather handle it in a calling function (like doSomething), you can use a promise to "return" a value.

function myProxy(param) {
    return new Promise((resolve, reject) => {
        myModule.getData(param, (err, data) => {
            if (!err) { // or however you determine an error occurred.
                resolve(data); // if I get data I want to return it to the proxy
            } else {
                reject(err); // if I get an err I want to return the error to the proxy
            }
        });
    });
}

function doSomething(param){
    myProxy(param).then(data => {
        // Handle the data here.
    }).catch(err => {
        // Handle the error here.
    });
}