javascript - Promise 既解决又拒绝
问题描述
似乎我的 Promise 同时返回 true 和 false。控制台返回“未定义”,然后在其下方返回“出现问题”。数据在这些下面返回,表明它实际上并没有等待 Promise。
这是被调用的函数:
module.exports = (url) => {
return new Promise((resolve, reject) => {
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
})
})
resolve()
return topsongs;
})
.catch(reject("something went wrong"))
})
}
来自来电者:
componentDidMount() {
const top_songs = topsongs('https://www.billboard.com/charts/hot-100')
.then(console.log(top_songs))
.catch(err => console.log(err))
}
谢谢,我是 Promises 的新手,并且几乎尝试了所有方法。尽管 async axios() 调用我有一个 Promise 的原因是它没有被异步执行并返回未定义的数据。
解决方案
.catch(reject("something went wrong"))
您需要将函数传递给catch
.
您正在立即调用 reject
并传递其返回值。
您还使用了嵌套的 Promise 反模式。
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"});
(用通用的“出现问题”替换抛出的错误似乎没有帮助。没有那个 catch 调用你可能会更好)
推荐阅读
- javascript - 如何在 Ejs 模板中打印 Web 抓取的项目?
- asp.net - MAC OS 上 Firefox 和 Chrome 的重音字母
- python - Pandas 行列转换
- android - 如何在配套设备配对屏幕中捕捉用户取消?
- graphql - 如何查询2个不同的图像?
- python - 为什么生成器表达式被称为?
- azure - 托管在 Azure 应用服务中的 .Net Core 的托管服务/后台服务正在停止
- terraform - 如何在 aws_eks_cluster 资源上启用 Windows 支持?
- html - Bootstrap:导航栏:导航侧菜单:在小屏幕上折叠
- reactjs - 使用反应找到的包从路径访问参数