Node.js中的CallbackHandler

时间:2017-05-23 07:59:57

标签: javascript node.js callback promise

我在异步网络连接的.js文件中有以下方法

function requestWatsonDiscovery(queryString) {
    console.log('Query =', queryString);
    if (typeof queryString !== 'undefined') {
        var discoveryUrl = `something`
        console.log('Total url =', discoveryUrl);
        var options = {
            host: 'gateway.watsonplatform.net',
            path: discoveryUrl,
            auth: auth
        };

        http.get(options, function(http_res) {
            // initialize the container for our data
            var data = "";

            // this event fires many times, each time collecting another piece of the response
            http_res.on("data", function(chunk) {
                // append this chunk to our growing `data` var
                //console.log(data);
                data += chunk;
            });

            // this event fires *one* time, after all the `data` events/chunks have been gathered
            http_res.on("end", function() {
                // you can use res.send instead of console.log to output via express
                //console.log(data);
                data = JSON.parse(data);
                watsonReturnedText = parseData(data);
                //console.log(watsonReturnedText);
                //returnResult();
            });
        });
    }
}

同时我在另一个.js文件中更新我的UI。我希望在上述异步方法完成后得到通知。我知道我可以使用回调/承诺来做它。你能告诉我写承诺或回电的语法。

2 个答案:

答案 0 :(得分:1)

简单地说,这应该让您基本了解演示中的回调

function requestWatsonDiscovery (queryString, callback){ // <- new param
    http.get(options, function (http_res) {
        var data = "";

        http_res.on("data", function (chunk) {
            data += chunk;
        });
        http_res.on("end", function () {
            var parseData =JSON.parse(data);
            callback(parseData); // <- usage of new param
        }); 
    });
}

requestWatsonDiscovery(null, function(result) {
    // result is your data;
    console.log(result);
});

答案 1 :(得分:-1)

这基本上是..

function requestWatsonDiscovery (queryString){
  return new RSVP.promise((resolve, reject) => {

    if (typeof queryString !== 'undefined') {
      var discoveryUrl = `something`

      var options = {
        host: 'gateway.watsonplatform.net',
        path: discoveryUrl,
        auth : auth
      };

      http.get(options, function (http_res) {
        var data = "";

        http_res.on("data", function (chunk) {
          data += chunk;
        });

        http_res.on("end", function () {
          data =JSON.parse(data);
          watsonReturnedText = parseData(data);
          resolve(watsonReturnedText);
        });
      });
    }
    else { reject(); }
  }); //end promise
}

当您致电requestWatsonDiscovery时,请执行此操作...

var watsonPromise = requestWatsonDiscovery(queryString);

watsonPromise.then((data) => { 
 //use your watson data
}).catch(() => {
 //manage the error
});