首页 > 解决方案 > 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 的原因是它没有被异步执行并返回未定义的数据。

标签: javascriptreactjspromisees6-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 调用你可能会更好)


推荐阅读