[我正在尝试使用sails.js(使用node.js)。我有一个控制器,如下所示。该控制器将在URL参数中传递的标准URL解析为ical_url
我试图解析它,并建立一个标准化的json objetc pe rmy需要。我有一个parse
功能仅暴露在此控制器之外。使用节点式npm包(https://www.npmjs.com/package/node-ical)解析内容。在ical.fromURL
方法中,我有一个回调函数初始化变量normalized_data
并在其中存储数据。我打算使用这些数据并调用decorate
方法进行一些处理,然后返回json。请查看以//>>>>>>
开头的行,按照我的意愿,我没有访问normalized_data
根据https://github.com/jens-maus/node-ical/blob/HEAD/index.js#L87 ical.fromURL
正在返回承诺但我很难理解如何使用该承诺中的数据。有人可以帮我进行此文件(尤其是parse
方法中的文件)所需的更改以符合我的期望吗?预先感谢。
/**
* IcalsController
*/
const ical = require('node-ical');
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat'];
function normalize(ev_obj) {
return {
"uid": ev_obj.uid,
"start": ev_obj.start.toDateString(),
"end": ev_obj.end.toDateString(),
"start_ts": ev_obj.start,
"end_ts": ev_obj.end,
"user": ev_obj.organizer.val.split("mailto:")[1].split("@")[0], //TODO - use regex for extraction
"summary": ev_obj.summary,
"categories": ev_obj.categories,
"all_day": (ev_obj["event-allday"] == "true")
}
}
function decorate(data) {
//do something here and return a json object
//return json_object;
}
module.exports = {
parse: function (req, res) {
if (req.param("ical_url") == undefined) {
return res.status(400).send("ical_url is missing");
}
ical.fromURL( //refer - https://github.com/jens-maus/node-ical/blob/HEAD/index.js#L87
req.param("ical_url"),
{},
function (err, data) {
let normalized_data = [];
for (let k in data) {
if (data.hasOwnProperty(k)) {
if (data[k].type == 'VEVENT') {
normalized_data.push(normalize(data[k]));
}
}
}
}
);
//>>>>>> Here I want to call decorate function and pass normalized_data as parameter
let result = decorate(normalized_data)
return res.send(result);
},
};
问题出在不考虑fromURL
方法的异步性质。
代码正在调用fromURL
,这将导致在将来某个时间该方法完成时调用回调,然后立即尝试将尚未接收到的数据作为对客户端的响应来发送。] >
您需要在异步操作完成并且实际上已经收到一些数据之后发送响应,更像这样:
parse: function (req, res) { if (req.param("ical_url") == undefined) { return res.status(400).send("ical_url is missing"); } ical.fromURL( //refer - https://github.com/jens-maus/node-ical/blob/HEAD/index.js#L87 req.param("ical_url"), {}, function (err, data) { let normalized_data = []; for (let k in data) { if (data.hasOwnProperty(k)) { if (data[k].type == 'VEVENT') { normalized_data.push(normalize(data[k])); } } } res.send(decorate(normalized_data)); << Response moved inside the callback. } ); }
尽管我实际上会建议,但您可以使用
async/await
关键字作为更简洁的解决方案。
parse: async function (req, res) { << Mark method as async
if (req.param("ical_url") == undefined) {
return res.status(400).send("ical_url is missing");
}
// Await keyword lets us use data from a promise more like it were simpler synchronous code
const raw_data= await ical.fromURL( //refer - https://github.com/jens-maus/node-ical/blob/HEAD/index.js#L87
req.param("ical_url"),
{});
let normalized_data = [];
// Do your normalization of raw_data here
return res.send(decorate(noramlized_data));}