所以我不得不在我的应用程序中调用两个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?
1条答案
按热度按时间ep6jt1vc1#
这里有些问题:
1.您不会从链式调用中返回任何内容-
.finally
必须返回一些内容才能填充变量。1.尽量避免混合
await
和.then
,因为这可能更难阅读和推理。如果您需要
code
来执行第二个API调用,则不需要将其存储在state中;它可以保留在useEffect函数中。例如: