【问题标题】:Async request in react-redux using async/awaitreact-redux 中的异步请求使用 async/await
【发布时间】:2020-04-26 19:29:55
【问题描述】:

我是 React 新手,我正在尝试对服务器进行 Api 调用,然后在我的组件中使用此数据。

我正在尝试使用 async await 来处理异步

const onNotifReceived = async (res) => {
    var updatedQueue = res.updatedQueue;
    updatedQueue["queueNewState"] = await getContactDetails(authClient, res.updatedQueue.queueNewState);
    console.log(JSON.parse(JSON.stringify(updatedQueue)))
    notifyQueue(updatedQueue); // redux dispatcher
}

我注意到 console.log(JSON.parse(JSON.stringify(updatedQueue))) 在函数 getContactDetails 内的其他 console.logs 之前运行。

但据我所知,await 应该在传递到下一行之前等待响应,但情况并非如此,而且我没有得到 updatedQueue["queueNewState"] 新状态的问题。

【问题讨论】:

    标签: javascript reactjs asynchronous redux


    【解决方案1】:

    也许getContactDetails()没有返回promise,但是里面有延迟操作。

    async function xd() {
        await xdd();
        console.log("after xdd");
    }
    function xdd() {
        setTimeout(() => {
            console.log("1000 later");
        }, 1000);
    }
    xd();
    // after xdd
    // (after 1 second)
    // 1000 later
    
    async function xd() {
        await xdd();
        console.log("after xdd");
    }
    function xdd() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log("1000 later");
                resolve();
            }, 1000);
        });
    }
    xd();
    // (after 1 second)
    // 1000 later
    // after xdd
    

    对于第一种情况,xdd 在 console.log("after xdd"); 之前运行,但 console.log("1000 later"); 将在 1 秒后出现。

    【讨论】:

    • 此外,具有then 函数的对象被视为与承诺相同。
    猜你喜欢
    • 2020-03-01
    • 2018-02-15
    • 2019-09-09
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 2016-12-04
    相关资源
    最近更新 更多