【发布时间】:2017-05-23 17:09:34
【问题描述】:
我在 .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。我希望在上述异步方法完成时收到通知。我知道我可以使用回调/承诺来做到这一点。你能告诉我写承诺或回调的语法吗?
【问题讨论】:
-
对承诺使用 RSVP。
-
请您详细说明一下。我是 javascript 编程新手
-
使用 Promises 作为 Promise,因为节点有原生 Promise
-
如果你想防止内存泄漏,应该是
.once('end')而不是on('end')。
标签: javascript node.js callback promise