javascript - 如何将一个异步函数的结果使用到另一个异步函数

标签 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 ) 上的纬度和经度坐标。我正在尝试使用坐标并将其输入到网址中,而不是使用硬编码的坐标。

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

  • 我尝试使用模板字符串使坐标动态化: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()

最佳答案

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

关于javascript - 如何将一个异步函数的结果使用到另一个异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58574008/

相关文章:

c# - 使用异步委托(delegate)进行异常处理

c# - 当线程为 'awaits' 时会发生什么

javascript - React autoFocus 将光标设置为输入值的开头

javascript - 计算融合表中点之间的距离

php - array_map 在类里面不起作用

mysql - 要运行的字符串

使用输入文件中的出现次数创建数组 (C)

javascript - Node.js 在 mysql 中使用异步/等待

javascript - 表单在弹出框中提交

javascript - querySelectorAll 是在多个图表中选择元素的好方法吗?