在第一个解决之前执行的承诺

时间:2021-05-21 12:44:21

标签: javascript react-native react-hooks

我正在尝试从 Json 中提取深层数据,但是当我导航到我的屏幕时,我的代码执行第一个承诺,但第二个承诺映射到我在前面设置的钩子中承诺。我试图弄清楚如何仅在第一个承诺得到解决时执行第二个承诺。 这是我的代码:

  const [tableHead, setTableHead] = useState('');
  const [performance, setPerformance] = useState('');
  const [performanceKpis, setPerformanceKpis] = useState('');

  useEffect(() => {
    async function getKpis() {
      const findData = await Promise.all(
        json.map((performance) => performance.performance)
      );
      setPerformance(...findData);

      const findValues = await Promise.all( <=============== This is the stuff 
        setPerformanceKpis(performance.map((performance) => performance.value))
      );
      // setPerformanceKpis(findValues);
    };
    getKpis()
  }, []);

我对 Promise 还很陌生。我不知道它是如何正常工作的。

[
  {
      "id": "3c20fbe3-fc59-433d-b349-6aa3b4a4c17b",
      "name": "20210504",
      "external_id": "3ad0c67e-170c-4ea8-afcc-850c94f449aa",
      "farm_id": "489cd6a6-db19-4a6f-bc95-1d981edc972f",
      "farm_name": "Granja Presence",
      "producer_id": null,
      "producer_name": "Produtor Granja Presence",
      "type": "limited",
      "finished": true,
      "walkthrough_available": false,
      "performance": [
          {
              "key": "AVERAGE_DATE_INPUT",
              "name": null,
              "abbreviation": null,
              "value": "2021-05-04T00:00:00",
              "measurement_unit": "date",
              "decimal_places": null,
              "is_critical": false
          },
          {
              "key": "AVERAGE_DATE_OUTPUT",
              "name": null,
              "abbreviation": null,
              "value": "2021-05-04T00:00:00",
              "measurement_unit": "date",
              "decimal_places": null,
              "is_critical": false
          },

这是我的 JSON 结构,我想提取性能数组中的对象。所以我制作了一张地图并将数据推送到我的 Hook,现在我试图在我的 Performance 数组中映射并将对象推送到我的钩子,稍后我将在表格中呈现。

1 个答案:

答案 0 :(得分:0)

我认为这里不需要 Promise。因为我没有看到您在 json.map 中进行任何 API 调用,也没有看到您的 performance.performance 是一个返回 Promise 的函数调用。

const getPerformanceValues = async () => {
   try {
     const json = await //your api call 
     const findData = json.map((performance) => performance.performance)
     setPerformance(findData);
     const findValues = findData.map((performance) => performance.value);
     setPerformanceKpis(findValues)
   } catch(error){
     // do something if api calls fails
   }
}


useEffect(() => {
  getPerformanceValues ();
}, []);