使用async / await处理axios拒绝

时间:2018-12-16 13:09:59

标签: reactjs react-native promise async-await axios

我正在使用axios调用api。我有一个单独的课程,如下所示:

export default class api {
    static instance = null;

    static getInstance() {
      if(this.instance == null) {
        this.instance = new api();
      }

      return this.instance;
    }

    wsCall(url, data) {
        var config = {
            method: "POST",
            baseURL:baseUrl,
            url: url,
            headers: { "Content-Type": "application/json" },
            timeout: 20000,
            data: {...data}
        };

        return axios(config);
    }
}

我还通过api类的构造函数中的axios interceptors对axios响应进行了一些更改:

    axios.interceptors.response.use(
        function (response) {
            if(response == null || response.data == null)
                Promise.reject([1, "error1"]);
            let responseJson = response.data;

            if (responseJson.status == 1) return responseJson.data;
            else Promise.reject([2, "error2"]);
        }, function (error) {
            return Promise.reject([3, "error3"]);
        }
    );

我还定义了函数来调用我的每个服务。例如,我有login这样的功能:

export function login(username, password) {
    return api.getInstance().wsCall(
        "/user/login",
        {
            username: username,
            password: password
        }
    );
}

现在,当我调用login并使用promise函数获得结果时,一切正常:

login("un", "pass")
    .then(response => {
        //success
    })
    .catch(([code, error]) => {
        //error
    });

但是当我用async/await调用它时,catch永远不会调用,并且我也不会得到错误。但是成功的结果是可以的:

try{
    var response = await login("un", "pass");

    //when there is no error the response is ok, but when it has error the response equals to undefined!
} catch(error) {
    //error part never run's
}

我的错误是什么?
预先感谢

0 个答案:

没有答案