首页 > 解决方案 > 从 Promise 返回数据并在 API 调用后将其存储在变量中

问题描述

我对 Promises 很陌生,在这里找到了许多示例如何访问始终使用console.log. 但我的目标是将结果存储在一个变量中并使用它。

getdata = () =>
  fetch(
    "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo"
  )
    .then(response => {
      if (response.status === 200) {
        return response.json();
      } else {
        throw new Error("This is an error");
      }
    })
    .then(data => {
      console.log(data);
    });

getdata();

此代码有效。你能帮我重写它,该getdata()函数允许我将结果存储在一个变量中。Return 不起作用,因为我将收到另一个待处理的 Promise。

标签: javascriptpromisees6-promise

解决方案


你可以这样做:

getdata = () =>
  fetch(
    "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo"
  ).then(response => {
    if (response.status === 200) {
      return response.json();
    } else {
      throw new Error("This is an error");
    }
  });

getdata().then(data => {
  //I can do whatever with data
});

当然,您还想处理请求失败的情况,因此您也可以链接一个.catch(). 或者,如果您为其配置了构建过程,则可以使用asyncawait因此您可以执行以下操作:

try {
  const data = await getdata();
} catch(err) {
}

这需要在标记为的函数中async


推荐阅读