【问题标题】:Why axios with async/await not working in this case?为什么带有 async/await 的 axios 在这种情况下不起作用?
【发布时间】:2020-04-25 13:38:48
【问题描述】:

我想在点击按钮时更改DoorState

发布API更改DoorState后,调用get API检查机器人状态。

其实DoorState 变了。 但console.log(after) 代码不变。为什么?

{
    deliveryPost.Delivery.status === 'assigned' &&
        (checkDoorState(deliveryPost.Delivery.postId) === 'closed' ? ( <
            >
            <
            button className = "bg-white text-teal-500 py-2 px-4 ml-2 border border-teal-500 rounded hover:bg-teal-500 hover:text-white"
            onClick = {
                () => clickRobotAction(deliveryPost.Delivery.postId, 'open')
            } >
            Open Door <
            /button> <
            />
        ) : ( <
            >
            <
            button className = "bg-white text-teal-500 py-2 px-4 ml-2 border border-teal-500 rounded hover:bg-teal-500 hover:text-white"
            onClick = {
                () => clickRobotAction(deliveryPost.Delivery.postId, 'close')
            } >
            Close Door <
            /button> <
            />
        ))
}
``
`

`
``
const clickRobotAction = async (postId: string, action: string) => {
    const appliedRobot = robots.find(robot => robot.postId === postId);
    const {
        robotId
    } = appliedRobot;

    try {
        await axios.post(`api/${robotId}/action/${action}`); // DoorState open <=> close
        const after = await axios.get('api/robots');

        console.log(after); // But not change in this log. Why?
    } catch (error) {
        console.error(error);
    }
};

【问题讨论】:

  • 您的代码似乎正确。你确定问题不在后端?你也可以发一下吗?编辑:也许你应该发帖api/robots/${robotId}/actions/...
  • 不应该在const after = await axios.get('api/robots'); 中为after 分配一个特定的机器人ID(也可能是它的状态)?对api/robots 的调用是否返回门状态??
  • 是的。 api/robots 有门状态作为响应。
  • 我认为 api/robots 不同步。如果我写 setTImeout(() => console.log(after), 1000},它会起作用。
  • axios.get() 是异步的,它返回一个 Promise。 try...catch 是同步的。也许当您 post 更改 DoorState 时,您的后端需要执行一个进程(数据库、硬件等),这比您调用 get 的时间要长。

标签: javascript reactjs typescript next.js


【解决方案1】:

我不确定,但我认为这是因为 axios.post 请求应该是 axios.get,因为您没有为对象添加第二个重载参数。由于您只是发送一个查询字符串,那么我认为它应该只是一个不确定的获取请求,尽管我希望这会有所帮助。

【讨论】:

  • 遗憾的是这个 api 的调用是正确的。实际上 doorState 是变化的。但该控制台不适用。
猜你喜欢
  • 2020-03-15
  • 2018-07-15
  • 2019-12-04
  • 2017-11-26
  • 2010-12-29
  • 1970-01-01
  • 2021-08-05
  • 2011-11-14
  • 1970-01-01
相关资源
最近更新 更多