如何使用从一个异步函数到另一个异步函数的结果

时间:2019-10-26 19:27:29

标签: javascript function async-await geolocation fetch

我正在尝试在另一个api(https://api.wheretheiss.at/v1/satellites/25544)的URL中使用ISS api(https://api.wheretheiss.at/v1/coordinates/37.795517,-122.393693)上的纬度和经度坐标。我正在尝试使用坐标并将其输入到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()

1 个答案:

答案 0 :(得分:1)

异步函数返回一个承诺,因此您可以使用。then()

您应该从 getISS 返回数据并使用 .then(),如下所示……

ido-file-name-all-completions

调用 getISS 函数,然后使用 then 调用带有必要数据的 getGeoLocation

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