【问题标题】:JS How to extract data from a promiseJS如何从promise中提取数据
【发布时间】:2020-10-14 02:50:57
【问题描述】:

我正在努力从 API 调用中提取数据。我需要它来返回一个键数组,但是当我尝试渲染时,我不断收到[object Promise]

const apiKey = '*****';
const container = document.getElementById('root');

const Yelp = {
  async search(term, location, searchBy) {
    let response = await fetch(`https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/search?term=${term}&location=${location}&sort_by=${searchBy}`, {
      headers: {
        Authorization: `Bearer ${apiKey}`
      }
    })

    if (response.ok) {
      let jsonResponse = await response.json()
      return jsonResponse.businesses.map(business => {
        return business
      })

    }
  }
}

console.log(Yelp.search('pasta', 'london', 'best_match'));

【问题讨论】:

  • Yelp.searchasync 因此返回一个 Promise .. 您可以等待该承诺(如果您在 async 函数中这样做)或使用承诺的 .then 方法来访问承诺的解决值
  • Yelp.search().then() ... 在 then() 中你会得到我认为的返回数据...

标签: javascript ajax api async-await


【解决方案1】:

由于 Yelp.search 函数是异步的,它总是会返回一个 Promise。这就是你在调用它后记录立即结果时遵守承诺的原因。相反,您应该像这样等待承诺:

Yelp.search('pasta', 'london', 'best_match').then(results => {
    console.log(results)
})

所以要回答你的问题,你可以调用 Promise 的 then() 方法来等待它的结果得到解决。 then 方法有两个参数。第一个是您提供的用于处理承诺结果的函数。第二个是您提供的用于处理 promise 返回的任何错误的函数。例如:

Yelp.search('pasta', 'london', 'best_match').then(results => {
    // handle the results
    console.log(results)
}, err => {
    // handle the error
    console.error(err)
})

您还可以通过调用 catch() 来捕获由 Promise 引发的异常,如下所示:

Yelp.search('pasta', 'london', 'best_match')
    .then(results => console.log(results), err => console.error(err))
    .catch(ex => console.error(ex))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 2021-09-21
    • 1970-01-01
    • 2021-01-09
    • 2020-04-14
    相关资源
    最近更新 更多