首页 > 解决方案 > React Native Axios 调用内部函数

问题描述

我试图将 AXIOS 函数的 POST 放在另一个函数中以多次重用它。但不幸的是它没有像我预期的那样工作(使用 FETCH 工作),

AXIOS CALL JS:

export async function post(apiRoute, body) {

    try {


        body = JSON.stringify(body);
        axios.post(apiRoute, body, httpOptions)
             .then((res)=>{
                console.log(res.data);                // I have data here
                return res.data;
             });
    }
    catch (err) {
        console.log(err);
        return err;
    }
}

来电者是:

    async DoLogin(userName, password) {
        
        var data = await post(url,{     // post is axios method defined above in another file
            UserName: userName,
            Password: password
        });


        return data;                // I have nothing here
    }

问题是我在 DoLogin 中未定义但在 POST 方法中获取了数据,似乎问题与时间有关,axions 返回一个在 DoLogin 中无法读取的承诺,我该怎么做?我通过 FETCH 做到了这一点,并且效果很好。

标签: reactjsreact-nativeasynchronousasync-awaitaxios

解决方案


尝试以这种方式使用 async-await。

export async function post(apiRoute, body) {

    try {
        const response = await axios.post(apiRoute, body, httpOptions)
        return response.data; 
    }
    catch (err) {
        return err;
    }
}

推荐阅读