useEffect等待异步函数的结果

时间:2019-12-16 11:48:28

标签: reactjs asynchronous post xmlhttprequest

我正在尝试在React应用中为POST请求创建一个函数(由于我在几个地方都需要它),它应该在useEffect语句中返回responseText。我搜索过的变体不能充当异步对象-在从服务器获取响应之前,将字符串console.log(“ JSON”,json)放入控制台 JSON undefined 中。

useEffect(() => {
        (async function() {
            try {
                const response = await post_return(postData);
                const json = await JSON.stringify(response);
                console.log("json", json);
            } catch (e) {
                console.error(e);
            }
        })();
    }, [postData]);
const API_URL_REGISTRATION = "https:.....";

export function post_return (dataPost)  {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", API_URL_REGISTRATION, true);

    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
            console.log("xhr.status", this.status);
            console.log("this.responseText", this.responseText);
            return  xhr.status
        }
    };
    xhr.onload = function () {
        console.log("xhr.status", this.status);
        console.log("this.responseText", this.responseText);
        return  xhr.status;
    };

    xhr.onerror = function () {
        alert('Error' + this.status);
    };
    xhr.send(JSON.stringify(dataPost));
}

也尝试过

导出异步函数post_return(dataPost){...

和:

xhr.onreadystatechange =异步函数()

我做错了什么? 谢谢,

2 个答案:

答案 0 :(得分:0)

post_return函数的第一件事是它立即返回undefined,因此response变量值实际上是undefined并调用了{{1}带有JSON.stringify的}也是undefined。您应该做的是更正undefined,以使其返回post_return

最简单的解决方案是像这样使用内置的Promise

fetch

答案 1 :(得分:0)

Rafal2228,感谢您的帖子,我根据需要采用了它

export async function post_return(url, dataPost) {
    const response = await fetch(url, {
        method: 'POST',
        body: JSON.stringify(dataPost),
        headers: {
            'Content-type': 'application/x-www-form-urlencoded'
        }
    });
    const json = await response.json();
    return {
        status: response.status,
        body: json
    };
}
useEffect(() => {
        (async function() {
            try {
                if (postData.email !== undefined)
                {
                    const response = await post_return(API_URL_REGISTRATION, postData);
                    // console.log("response", response);
                    setshowLoader(false);
                    if (response.status === 200) {
                        navigate("/login")
                    } else alert(response.body);
                }
            } catch (e) {
                console.error('Ошибка ' , e);
            }
        })();
    }, [postData]);