簡體   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/坐標/37.795517,-122.393693 )。 我正在嘗試使用坐標並將它們輸入 url 而不是使用硬編碼的坐標。

這是我到目前為止所做的......

  • 我嘗試使用模板字符串使坐標動態化: https://api.wheretheiss.at/v1/coordinates/${latitude},${longitude}
  • 我制作了兩個單獨的異步等待函數:(1) getISS() 獲取緯度/經度坐標和 (2) getGeoLocation() 獲取這些坐標並獲取 country_code/timecode_id 數據
  • 我還嘗試使用緯度、經度調用 getGeoLocation() 作為 arguments 並將它們傳遞給參數的緯度和經度,但這只會導致 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()

異步函數返回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 function,然后使用必要的數據調用getGeoLocation

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM