异步功能未执行

时间:2020-06-22 10:17:27

标签: reactjs redux async-await try-catch

我正在尝试通过Redux动作从SQL Server提取数据。 我的问题是,异步函数内部绝对没有运行。 “ try”分支和“ catch”分支都不是

export function fetchMessages() {
    console.log("Fetching messages...");


    let tempDisp = async dispatch => {
        //This way we can show a loading screen
        console.log("Before try catch")
        dispatch(fetchMessagesBegin());
        try {
            const res = await fetch('http://185-220-204-106.cloud-xip.io:5000/messages/all');
            const json = await res.json();
            console.log("json is: ", json);
            console.log("The json object:", json);
            dispatch(fetchMessagesSuccess(json));
            return json.messages;
        }
        catch (error) {
            dispatch(fetchMessagesFailure(error));
            console.log("Error: ", error);
        }
    };

    console.log("The tempDisp is: ",tempDisp);
    return tempDisp;
}

我得到的控制台输出是

Fetching messages... main.chunk.js:292:11
The tempDisp is: function tempDisp()

因此,在异步运行之前,try ... catch运行之前以及未在Error分支运行之前,console.log也会运行。我正在尝试从useEffect()调用fetchMessages,但是我也在渲染React应用之前尝试了它,结果也是一样。我不知道是什么原因造成的。任何帮助表示赞赏。

更新

在阅读this thread之后,我重新编写了如下代码:

export const fetchMessages = messages => async (dispatch) => {
    //This way we can show a loading screen
    console.log("Before try catch");
    dispatch(fetchMessagesBegin());
    try {
        const res = await fetch('http://185-220-204-106.cloud-xip.io:5000/messages/all');
        const json = await res.json();
        console.log("json is: ", json);
        //We might not have a top level container, like 'messages'
        console.log("The json object:", json);
        dispatch(fetchMessagesSuccess(json));
        //return json.messages;
    }
    catch (error) {
        dispatch(fetchMessagesFailure(error));
        console.log("Error: ", error);
    }
}

它仍然无法正常工作,而且我也没有任何console.logs。

更新 这是我在调用fetchMessages的地方:

function App({isLoggedIn}) {
  let testingOnly = ["hello"];

  useEffect(() => {
    testingOnly = fetchMessages();

    console.log(isLoggedIn);
  });

[... React return ...]



const mapStateToProps = state => ({
    isLoggedIn: state.isLoggedIn,
    isServerError: state.isServerError,
    serverError: state.serverError,
    loginAttempt: state.loginAttempt,
    messages: state.messages
});

export default connect(mapStateToProps)(App);

1 个答案:

答案 0 :(得分:0)

问题是,我没有安装redux-thunk。

import thunk from 'redux-thunk';

然后您需要添加中间件来存储

let store = createStore(reducer, applyMiddleware(thunk));

此后,它起作用了。