调用以下方法时:
getLyrics: async function(song) {
const body = await this.getSongBody(song);
const lyrics = await cheerio.text(body('.lyrics'));
return lyrics;
}
因此:
genius.getLyrics('What a wonderful')
.then((res) => console.log(res))
.catch((err) => console.log(err.message));
一切正常,控制台中弹出Louise Armstrong的“多么美好的世界”的歌词。
但是,当我运行相同的代码但在“ cheerio.text ...”前面没有“ await”时,有时会产生歌词,而有时会在控制台中显示“ undefined”。现在让我抓狂了一段时间的是,“ cheerio.text ...”没有返回承诺(尽管“ getSongBody”可以实现),所以据我所知,不需要“等待”它完成。
我显然缺少有关异步/等待的东西,但不知道是什么。任何帮助将不胜感激!
谢谢
编辑:添加了可重复的示例,如下所示:
const fetch = require('node-fetch');
const cheerio = require('cheerio');
// API
function geniusApi(token) {
this._token = token;
this._auth = {'Authorization': 'Bearer ' + this._token};
};
geniusApi.prototype = {
getSongURL : async function(search_keyword){
const res = await fetch('https://api.genius.com/search?q=' +
search_keyword,{headers: this._auth});
const body = await res.text();
const body_parsed = JSON.parse(body);
if (body_parsed.response.hits.length == 0){
console.log('No such song found');
throw Error('No such song found');
}
const url = body_parsed.response.hits[0].result.url;
return url;
},
getSongBody: async function (song){
const url = await this.getSongURL(song);
const response = await fetch(url);
const body = await response.text();
const body_parsed = cheerio.load(body);
return body_parsed;
},
getLyrics: async function(song) {
const body = await this.getSongBody(song);
const lyrics = cheerio.text(body('.lyrics'));
return lyrics;
}
}
// TEST EXAMPLE
const token =
'OTh1EYlsNdO1kELVwcevqLPtsgq3FrxfShIXg_w0EaEd8CHZrJWbWvN8Be773Cyr';
const genius = new geniusApi(token);
genius.getLyrics('What a wonderful')
.then((res) => console.log(res))
.catch((err) => console.log(err.message));
对于任何偶然发现同一问题的人,这种情况下的问题都与异步,promise或任何其他JS功能无关。只是巧合的是,代码在使用异步时已正确运行,后来才发现它也不总是与异步一起工作。
原因很简单,我用来获取数据的Genius API将为相同的API查询返回不同的源代码。
返回了两个不同的源代码,其中一个包含一个称为“歌词”的div,而另一个则没有。因此,有时歌词是使用cheerio来找到的,而其他时候却不是。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句