Fetch api 不返回数据而是 Promise

问题描述 投票:0回答:1

我通过创建异步函数来使用 fetch 调用 fakestoreapi。我正在返回await response.json();但最后我得到了一个承诺。即使我尝试在该函数之外声明一个变量并分配 data =等待response.json();,它也是未定义。但是当我 console.log(data) 时,它将实际数据记录到控制台。我的代码是:

//let products = [];

const getProducts = async () => {
 const response = await fetch('https://fakestoreapi.com/products');
 const data = await response.json();
 console.log(data);// this works and logs data to console
 //products = data; this is undefined when logged to console.
 return data; // this gives back a promise.
}

console.log(getProducts());
console.log(products);
javascript json async-await fetch
1个回答
0
投票

根据文档

每次调用异步函数时,它都会返回一个新的 Promise,该 Promise 将使用异步函数返回的值进行解析,或者因异步函数内未捕获的异常而被拒绝。

因此,异步函数总是返回一个 Promise。

您需要先解决它:

//let products = [];

const getProducts = async () => {
   const response = await fetch('https://fakestoreapi.com/products');
   const data = await response.json();
   console.log(data);// this works and logs data to console
   //products = data; this is undefined when logged to console.
   return data; // this gives back a promise.
}

getProducts().then(products => {
    console.log(products);
});
© www.soinside.com 2019 - 2024. All rights reserved.