我想知道Node.js中的控制流。但这对我来说太难了。
我正在使用google-alerts-api
npm制作Google警报抓取工具。
我从这个npm得到警报的名字和警报的rss。以下是我的预期流程。
name
和rss
name
数组result
rss
并获取XML文档。entry list
entry list
,获取title
和href
entry list
由包含title
和href
title
数组href
和result
get_result
时,我可以获得result
数组。我的预期结果数组如下所示。因为我会在电子表格中推送此结果,并且api应该像这样使用。
[ [name1], [title], [href], [title], [href], ....
, [name2], [title], [href], [title], [href], ...
, ... ]
我的代码
const alerts = require('google-alerts-api');
const config = require('./config.js');
const parser = require('xml2json');
const request = require('request')
const Entities = require('html-entities').AllHtmlEntities;
alerts.configure({
mail: config.mail,
password: config.pass
});
externalCaller();
function externalCaller(){
getResult().then(function(arr){
console.log(arr);
});
}
var result = [];
function getResult(){
return new Promise(function(resolve, reject){
alerts.sync((err) => {
if(err) return console.log(err);
const alertList = alerts.getAlerts();
alertList.reduce(async function(lastPromise, elem){
await lastPromise;
var name = elem.name;
var rss = elem.rss;
if(name != config.mail){
result.push(['']);
result.push([name]);
result.push(['']);
return getXML(rss)
.then(printElem);
}
}, Promise.resolve());
resolve(result);
});
});
}
function getXML(rssUrl){
return new Promise(function(resolve, reject){
request(rssUrl, function (error, response, body) {
if(error || (response && response.statusCode != 200)){
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
reject(error);
}
json = parser.toJson(body);
parsedJson = JSON.parse(json);
entry = parsedJson.feed.entry;
if(entry)
resolve(entry);
});
});
}
function printElem(entry){
entry.forEach(function(entry){
title = Entities.decode(entry.title.$t);
title = title.replace(/<b>|<\/b>/g, '');
result.push([title]);
result.push([entry.link.href]);
});
}
我如何正确编码?