2 回答

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超7個(gè)贊
.catch(reject("something went wrong"))
您需要將函數(shù)傳遞給 。catch
您正在立即調(diào)用并傳遞其返回值。reject
您還在使用嵌套的承諾反模式。
axios返回一個(gè)承諾。無(wú)需創(chuàng)建另一個(gè)。
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"});
(將拋出的錯(cuò)誤替換為通用的“出現(xiàn)問(wèn)題”似乎沒(méi)有幫助。如果沒(méi)有那個(gè)接聽(tīng)電話,你可能會(huì)過(guò)得更好)

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
你已經(jīng)有了一個(gè)承諾,只是回報(bào)它。
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;
})
而僅僅對(duì)于“句法糖”,使所有內(nèi)容都更容易閱讀:async/await
module.exports = async (url) => {
const { data } = await axios({method:'get',url});
const $ = cheerio.load(data);
...
return topsongs;
}
添加回答
舉報(bào)