将 Axios promise 转换为常规 JSON 数组

Convert an Axios promise to a regular JSON array

我正在尝试 return 来自函数的数据,但它给我带来了问题。

我需要此功能才能 return JSON,但它 return 是一个承诺。

函数如下:

import axios from 'axios';

const fetchData = async () => {
  const result = await axios(
    'https://localhost:44376/api/parts',
  );
  return JSON.stringify(result, null, 2);
};

export default fetchData;

当我尝试使用 returned 数据时抛出此错误:

Uncaught TypeError: data.map is not a function

当我写到控制台时,这是我看到的:

data from machineParts API call:

Promise {<pending>}
 [[PromiseStatus]]: "resolved"
    [[PromiseValue]]: {"data": [ { "id": 5, "title": "Steel Rods", "partId": 39482  etc...

但这就是我需要的 return:

data from machineParts API call: (7) [ {...}, {...}, {...}, {...}, {...}, {...}, {...}]

0:
   id: 5
   title: "Steel Rods"
   partId: 39482

1:
   id: 23
   title: "Honed Cylinder head"
   partId: 23412      

等...

是否可以将 promise 转换为 JSON 数组?

谢谢!

答案在您共享的控制台中,以 data from machineParts API call: 开头的行。该数组嵌套在 data 属性下。

您还 JSON.stringifying 结果,这将使它成为一个字符串,而不是字符串或对象。这就是您看到 data.map is not a function 错误的原因,因为 string 没有名为 map.

的原型方法

要修复,请将 return JSON.stringify(result, null, 2); 更改为 return result.data;

asyncawait 只是处理承诺的不同语法,'await' 或多或少与在调用 .then 时链接 .then 相同=14=]。像这样的东西应该在模块中工作:

const fetchData = async () => {
  const response = await axios.get('https://localhost:44376/api/parts');
  return response.data;
};

因为 fetchData() 是一个 async 函数,它会 return 一个 Promise,所以调用代码要么必须 await 结果,要么使用 .then 语法访问结果数据。

您只想在调用 fetchData 函数后调用 .then()

// fetchData.js
import axios from "axios";

const fetchData = async () => {
  const result = await axios(
    'https://localhost:44376/api/parts',
  );
  // return the result
  return result;
};

export default fetchData;

现在像这样将其导入到您的组件中:

// App.js 
import fetchData from './fetchData' // fetchData path

const App = () => {
  const [data, setData] = React.useState([])

  React.useEffect(() => {

   fetchData().then(res => {
     setData(res.data)
   })
  },[])

  return (
    <div>
      <pre>
        <code> {JSON.stringify(data, null, 2)} </code>
      </pre>
    </div>
  )
}

export default App

参见 sandbox 示例。