【问题标题】:How to use result from one async function to another如何将一个异步函数的结果用于另一个
【发布时间】:2019-10-27 04:06:08
【问题描述】:

我正在尝试在另一个 api (https://api.wheretheiss.at/v1/coordinates/37.795517,-122.393693) 的 url 中使用 ISS api (https://api.wheretheiss.at/v1/satellites/25544) 上的纬度和经度坐标。我正在尝试使用坐标并在 url 中输入它们,而不是使用硬编码的。

这是我到目前为止所做的......

  • 我尝试使用模板字符串来使坐标动态化:https://api.wheretheiss.at/v1/coordinates/${latitude},${longitude}
  • 我创建了两个单独的异步等待函数:(1) getISS() 获取纬度/经度坐标和 (2) getGeoLocation() 获取这些坐标并获取 country_code/timecode_id 数据
  • 我还尝试使用纬度、经度作为参数调用 getGeoLocation(),并将它们传递给参数的纬度和经度,但这只会导致 500 错误

注意

const api_url_id = 'https://api.wheretheiss.at/v1/satellites/25544'

//async await getISS function
async function getISS() {
    const response = await fetch(api_url_id)
    const data = await response.json()
    const {
        latitude,
        longitude,
        velocity,
        visibility
    } = data
}

async function getGeoLocation(latitude, longitude) {
    const response2 = await fetch(`https://api.wheretheiss.at/v1/coordinates/${latitude},${longitude}`)
    const data2 = await response2.json()
    const {
        timezone_id,
        country_code
    } = data2

    console.log(data2.timezone_id,country_code)
}

getGeoLocation(data.latitude, data.longitude)

getISS()

【问题讨论】:

  • 第二个请求获得 500 内部服务器错误,具有特定的经纬度...

标签: javascript function async-await geolocation fetch


【解决方案1】:

async 函数返回 promise,因此您可以使用 .then()

你应该从 getISS 返回数据并使用 .then(),像这样...

// getISS function returns data
async function getISS() {
  const response = await fetch(api_url_id);
  const data = await response.json();
  return data;
}

调用您的 getISS 函数,使用 then 稍后使用必要的数据调用 getGeoLocation

getISS().then(({ latitude, longitude }) => {
  getGeoLocation(latitude, longitude);
});

【讨论】:

  • 我已经尝试过了,我可以使用 getGeoLocation 中的坐标。但是,我仍然收到错误:requests.js:18 GET api.wheretheiss.at/v1/coordinates/…500 (Internal Server Error) getGeoLocation @ requests.js:18 (anonymous) @ requests.js:32 Promise.then (async) (anonymous) @ requests.js:28 requests.js:24 Uncaught (in promise) 错误:无法在 getGeoLocation (requests.js:24) 获取 ISS 数据
  • 是的,我注意到了。如果您尝试使用其他坐标,则可以。所以,你的代码现在可以了。也许服务给了你错误的坐标,或者 getGeoLocation 只是给出了 500 和某些(受限)坐标
  • 我发现如果坐标在水体上方,则会出现错误。太令人沮丧了,但我最终想通了!
猜你喜欢
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
  • 2019-06-30
  • 1970-01-01
  • 2022-06-21
  • 2019-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多