2 回答
TA贡献1847条经验 获得超7个赞
.catch(reject("something went wrong"))
您需要将函数传递给 。catch
您正在立即调用并传递其返回值。reject
您还在使用嵌套的承诺反模式。
axios返回一个承诺。无需创建另一个。
module.exports = (url) =>
axios({
method: "get",
url: url,
})
.then((response) => {
const html = response.data;
const $ = cheerio.load(html);
const songtable = $(".chart-list__elements > li");
const topsongs = [];
songtable.each(function () {
const rank = $(this).find(".chart-element__rank__number").text();
if (rank == 11) return false;
const name = $(this).find(".chart-element__information__song").text();
const artist = $(this)
.find(".chart-element__information__artist")
.text();
topsongs.push({
rank,
name,
artist,
});
});
return topsongs;
})
.catch(() => {throw "something went wrong"});
(将抛出的错误替换为通用的“出现问题”似乎没有帮助。如果没有那个接听电话,你可能会过得更好)
TA贡献1796条经验 获得超4个赞
你已经有了一个承诺,只是回报它。
return axios({
method: 'get',
url: url
})
.then(response => {
const html = response.data
const $ = cheerio.load(html)
const songtable = $('.chart-list__elements > li')
const topsongs = []
songtable.each(function () {
const rank = $(this).find('.chart-element__rank__number').text()
if (rank == 11) return false;
const name = $(this).find('.chart-element__information__song').text()
const artist = $(this).find('.chart-element__information__artist').text()
topsongs.push({
rank,
name,
artist
})
})
return topsongs;
})
而仅仅对于“句法糖”,使所有内容都更容易阅读:async/await
module.exports = async (url) => {
const { data } = await axios({method:'get',url});
const $ = cheerio.load(data);
...
return topsongs;
}
添加回答
举报