2017-09-08 26 views
0

到目前爲止,對於我來說,Node Worker的概念就是那些聽起來很有趣的事情之一,而且我會在一天之內發現它。如何在Wakanda中使用Node Worker

那一天來了,我正在尋求一些幫助。

我需要調用一個Web服務,然後處理返回的數據。我可以用XMLHttpRequest調用服務,但是我必須從中獲取有用的數據。

有一個很好的節點模塊,既可以調用服務,也可以用一次調用返回有用形式的數據。

我可以設置Node worker(在Wakanda)來做到這一點並驗證它是否有效。

我的問題是處理代理中的異步調用。

到節點模塊的調用看起來是這樣的:

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 
 
});

所以我的包裝的代碼看起來是這樣的:

function doSomething(param){ 
 

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

這一切聽起來像我應該知道該怎麼做。不過,我認爲我正在爲新事物掙扎,讓自己陷入困境。 PS:我沒有嘗試過Threadify,但無法弄清楚如何讓工作人員返回收到的錯誤。

我真的很感激任何幫助或指針在這裏。

回答

2

如果我正確理解您的問題,則不能在異步調用完成後從函數返回值。您需要處理myModule.getData回調中的數據。

如果您希望在調用函數(如doSomething)中處理它,您可以使用承諾來「返回」一個值。

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. 
    }); 
} 
+0

是的,看起來像。謝謝傑夫。 –