我目前有两个包含promise的函数:
function getLyrics(url) {
youtubedl.getInfo(url, function (err, info) {
// handle errors here
if (err) {
console.log(err);
throw "Error retrieving lyrics (youtube-dl)";
} else {
var fields = info.title.split('-');
var artist = sanitizeArtistOrTitle(fields[0].trim());
// TODO: handle possibility of - in artist/song name
var title = sanitizeArtistOrTitle(fields[1].trim());
const options = {
apiKey: geniusKey,
title: title,
artist: artist,
optimizeQuery: true
};
geniusSong(options).then(function (result) {
urlFields = result.url.split('/');
// check if the name of the song and artist are in the url
// since the api seems to return a random lyric page
// when the actual page cannot be found
var titleAndArtist = urlFields[3].split('-').join(' ').toLowerCase();
if (titleAndArtist.includes(artist.toLowerCase()) &&
titleAndArtist.includes(title.toLowerCase())) {
// get the lyrics and write to a file
writeLyrics(options);
} else {
throw "Lyrics page does not match the song details"
}
}).catch(function (err) {
console.log(err);
throw "wtf going on";
})
}
})
}
function writeLyrics(options) {
geniusLyrics(options)
.then(lyrics => sanitizeLyrics(lyrics))
.then(sanitizedLyrics => fsPromise.writeFile("../aux_files/words.txt",
sanitizedLyrics.toString()))
.then(console.log("written to file"))
.catch(function (err) {
console.log(err);
throw "Could not lyrics to file";
});
}
首先,我在writeLyrics
中呼叫getLyrics
的方式安全吗?我应该使用异步/等待吗?接下来,我正在使用express.js,我想在中间件函数中调用getLyrics
并捕获任何错误。 try / catch块不起作用,那么我应该怎么做?