簡體   English   中英

從掛起的承諾中返回數據

[英]Return data from a pending promise

嘗試將響應存儲到變量中。 不知道我做錯了什么。 任何幫助,將不勝感激。

async function fetchData(url) {
  const response = await fetch(url);

  if (!response.ok) {
    const message = `An error has occured: ${response.status}`;
    throw new Error(message);
  }

  const data = await response.json();
  return data;
}

async function getActivities() {
  let response = null;
  try {
    response = await fetchData("https://www.boredapi.com/api/activity");
    return response;
  } catch (error) {
    throw error;
  }
}

let data = getActivities();
console.log(data);

您將不得不等待從getActivities返回的承諾解決。 由於您將該函數標記為async ,它將返回一個解析為函數返回值的承諾。

例如:

getActivities()
    .then(data => console.log(data));

或者,將您的應用程序邏輯包裝到一個async函數中,這將允許您使用await

async function main() {
  let data = await getActivities();
  console.log(data);
}
main();

一旦頂級等待成為一件事,將您的邏輯包裝在主函數中將是不必要的。

使用您在函數中使用的相同邏輯, console.log()將在您的數據返回之前執行良好。

您可以使用.then()

getActivities().then(data => 
{ console.log(data);
});

或者如果你想使用另一個async/await

(async randomFunction() {
let data = await getActivities();
console.log(data);
}());

暫無
暫無

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

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