axios 无法按顺序调用异步函数(API调用)

plupiseo  于 2023-03-02  发布在  iOS
关注(0)|答案(1)|浏览(195)

所以我不得不在我的应用程序中调用两个API。第一个是POST请求,它创建了一个新的游戏模型。第二个是GET请求,它使用了第一个请求中的值。我试图编写一个函数,以便它可以被顺序调用。但是它似乎不能正常工作:(
功能和使用状态

const dateTime = new Date().toJSON();
  const [code, setNewCode] = useState("");
  const [gameData, setGameData] = useState<any[]>([]);

  useEffect(() => {
    const asyncFunction = async () => {
      try {
        const firstResponse = await axios
          .post(apiUrl + "/games", {
            game: {
              name: dateTime,
            },
          })
          .then(function (response) {
            console.log(response.data.code);
            setNewCode(response.data.code);
          })
          .catch(function (error) {
            console.log(error);
          })
          .finally(() => {
            console.log(code);
          });
        const thirdResponse = await axios
          .get(apiUrl + "/games/" + code)
          .then(({ data }) => {
            console.log(JSON.stringify(data));
            let newData = JSON.stringify(data);
            setGameData(newData);
          })
          .catch((error) => console.error(error))
          .finally();
        console.log("Get is done");
      } catch (error) {
        return error;
      }
    };
    asyncFunction();
  }, []);

这是我在控制台中得到的日志:

LOG ST231 // code that is taken from json.response from POST request
LOG       // somehow empty value of code state that should've been updated by the POST request
LOG {"id":6,"name":"2023-02-28T12:55:01.221Z","code":"BX892","fight":false,"turn":0,"created_at":"2023-02-28T12:55:01.326Z","updated_at":"2023-02-28T12:55:01.326Z","user_id":1,"status":"active","players":[],"monsters":[]} // response from GET request. Why is the code "BX892"? Where did is take it? How is it possible?
ep6jt1vc

ep6jt1vc1#

这里有些问题:

  1. Setting state does not happen immediately.请参阅链接,了解为什么您的状态在设置后会立即记录旧值。
    1.您不会从链式调用中返回任何内容-.finally必须返回一些内容才能填充变量。
    1.尽量避免混合await.then,因为这可能更难阅读和推理。
    如果您需要code来执行第二个API调用,则不需要将其存储在state中;它可以保留在useEffect函数中。例如:
const dateTime = new Date().toJSON();
  const [gameData, setGameData] = useState<any[]>([]);

  useEffect(() => {
    const asyncFunction = async () => {
      try {
        // removed .then/.catch blocks - if there's an error,
        // it will be caught by the outer try/catch.  This ensures
        // firstResponse will be populated when the next call is made,
        // and setGameDate won't be called if there's an error there
        const firstResponse = await axios
          .post(apiUrl + "/games", {
            game: {
              name: dateTime,
            },
          });
        const thirdResponse = await axios
          .get(apiUrl + "/games/" + firstResponse.data.code);
        const newData = JSON.stringify(thirdResponse.data);
        setGameData(newData);
        console.log("Get is done");
      } catch (error) {
        console.log(error);
        return error;
      }
    };
    asyncFunction();
  }, []);

相关问题