简体   繁体   English

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

[英]How to use result from one async function to another

I am trying to use the latitude and longitude coordinates on an 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 ). I am trying to use the latitude and longitude coordinates on an ISS api ( https://api.wheretheiss.at/v1/satellites/25544 ) in the url of another api (https://api.wheretheiss.at/v1/坐标/37.795517,-122.393693 )。 I am trying to use the coordinates and input them in the url instead of using the hard coded ones.我正在尝试使用坐标并将它们输入 url 而不是使用硬编码的坐标。

This is what I have done so far...这是我到目前为止所做的......

  • I have tried using a template string to make the coordinates dynamic: https://api.wheretheiss.at/v1/coordinates/${latitude},${longitude}我尝试使用模板字符串使坐标动态化: https://api.wheretheiss.at/v1/coordinates/${latitude},${longitude}
  • I have made two separate async await functions: (1) getISS() to get the lat/ lon coordinates and (2) getGeoLocation() to take those coordinates and get the country_code/ timecode_id data我制作了两个单独的异步等待函数:(1) getISS() 获取纬度/经度坐标和 (2) getGeoLocation() 获取这些坐标并获取 country_code/timecode_id 数据
  • I have also tried calling the getGeoLocation() with latitude,longitude as arguments and passing them into latitude and longitude for the parameters, but this only results in a 500 error我还尝试使用纬度、经度调用 getGeoLocation() 作为 arguments 并将它们传递给参数的纬度和经度,但这只会导致 500 错误

Note笔记

 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 functions returns a promise , so you can use .then()异步函数返回promise ,因此您可以使用 .then ()

You should return the data from getISS and use .then() , like this...您应该从getISS返回数据并使用 .then () ,就像这样......

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

Call your getISS function, using then to later call getGeoLocation with the necessary data调用您的getISS function,然后使用必要的数据调用getGeoLocation

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM