简体   繁体   English

Promise 既解决又拒绝

[英]Promise both resolves and rejects

It seems as though my Promise is simultaneously returning true and false.好像我的 Promise 同时返回真假。 The console is returning "undefined" and then right underneath it's returning "something went wrong".控制台返回“未定义”,然后在其下方返回“出现问题”。 The data is returned underneath these, showing that it's not actually waiting on the Promise.数据在这些下方返回,表明它实际上并没有在 Promise 上等待。

Here's the function being called:这是 function 被调用:

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"))
    })
}

From the caller:来自来电者:

componentDidMount() {
    const top_songs = topsongs('https://www.billboard.com/charts/hot-100')
    .then(console.log(top_songs))
    .catch(err => console.log(err))
  }

Thanks, I'm new to Promises and have tried nearly every method of doing this.谢谢,我是 Promises 的新手,并且几乎尝试了所有方法。 The reason that I have a Promise despite the async axios() call is that it wasn't being performed asynchronously and returned undefined data.尽管有 async axios() 调用,但我有一个 Promise 的原因是它没有异步执行并返回未定义的数据。

.catch(reject("something went wrong"))

You need to pass a function to catch .你需要通过一个functioncatch

You are calling reject immediately and passing its return value.您正在立即调用reject并传递其返回值。


You are also using the nested promise anti-pattern.您还使用了嵌套的 promise 反模式。

axios returns a promise. axios返回 promise。 There is no need to create another one.无需创建另一个。


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"});

(Replacing the thrown error with the generic "something went wrong" doesn't seem helpful. You'd probably be better off without that catch call at all) (用通用的“出现问题”替换抛出的错误似乎没有帮助。没有那个 catch 调用你可能会更好)

You already have a promise, just return it.已经有一个 promise,只需退回它。

  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;
      })

And just for "syntactic sugar", async/await makes everything a little easier to read:仅仅为了“语法糖”, async/await让一切都更容易阅读:

module.exports = async (url) => {
   const { data } = await axios({method:'get',url});
   const $ = cheerio.load(data);

   ...

   return topsongs;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM