如何将一个异步函数的结果用于另一个

How to use result from one async function to another

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

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

备注

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()

async 函数 return 是一个 promise,所以你可以使用 .then()

你应该 return 来自 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);
});