Async function must return a boolean value

时光总嘲笑我的痴心妄想 提交于 2021-01-29 06:31:09

问题


I have a method that I am calling on the onsubmit event in the form tag.

So I need a true or false to be returned from the method.

I use an API to retrieve data, and according to the response from the API, I return true or false. But because it is an async function thats running, I cant get it right to wait for the response from the API, analyze it and then return my decision.

Any ideas on how I could solve this problem

function GetPolygonID()
            {
                document.getElementById("displayerror").innerHTML = "";
                var retrievedpoly = document.getElementById('polygondetails').value;
                var parts = retrievedpoly.split('coordinates');
                var parttoadd = parts[1].substring(0, parts[1].length - 2) + "}";
                console.log(parttoadd);

                var myx = '{"name":"Polygon OneTwoThree","geo_json":{"type":"Feature","properties":{},"geometry":{"type":"Polygon","coordinates' + parttoadd;
                var url = 'http://api.agromonitoring.com/agro/1.0/polygons?appid=apiid';

                const request = async() => {
                    const response = await fetchPoly(url, myx);
                    const data = await response.json();
                    const errorCheck = await CheckInfo(data);
                    console.log("2: " + errorCheck);
                    return await errorCheck;
                };
                return request();

            }


            function CheckInfo(data)
            {
                let flag = false;
                console.log(data);
                if (JSON.stringify(data).includes("Geo json Area is invalid. Available range: 1 - 3000 ha"))
                {
                    var myval = JSON.stringify(data);
                    //myval = myval.replace(/\\n/g,"<br/>");
                    parts = myval.split("\\n ").join(",").split("\\n");
                    console.log(parts);
                    var todisplay = parts[1].substring(10);
                    todisplay += ("<br/>" + parts[2].substring(10).replace(",", "<br/>").replace("c", "C"));
                    console.log(todisplay);
                    document.getElementById("displayerror").innerHTML = todisplay;
                } else
                {
                    flag = true;
                }
                console.log("1:" + flag);
                return flag;
            }

            function fetchPoly(url, data)
            {
                return fetch(url, {
                    method: "POST", // *GET, POST, PUT, DELETE, etc.
                    mode: "cors", // no-cors, cors, *same-origin
                    cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
                    credentials: "same-origin", // include, *same-origin, omit
                    headers: {
                        "Content-Type": "application/json"
                                // "Content-Type": "application/x-www-form-urlencoded",
                    },
                    redirect: "follow", // manual, *follow, error
                    referrer: "no-referrer", // no-referrer, *client
                    body: data // body data type must match "Content-Type" header
                });
            }

I did try it with .then(), originally, then I broke it down like this, as I thought it would be easier to return a value here.

Essentially I need GetPolygonID() to return a boolean which it gets from CheckInfo(). CheckInfo() determines if the form should submit or not

Any thought on how I could fix this?

Thank You


回答1:


GetPolygonID() function returns a Promise, so it must be either called with await or you can call then upon it:

var res = await GetPolygonID();

GetPolygonID().then(res => console.log(res));

You can make the whole function async:

async function GetPolygonID() {
    document.getElementById("displayerror").innerHTML = "";
    var retrievedpoly = document.getElementById('polygondetails').value;
    var parts = retrievedpoly.split('coordinates');
    var parttoadd = parts[1].substring(0, parts[1].length - 2) + "}";
    console.log(parttoadd);

    var myx = '{"name":"Polygon OneTwoThree","geo_json":{"type":"Feature","properties":{},"geometry":{"type":"Polygon","coordinates' + parttoadd;
    var url = 'http://api.agromonitoring.com/agro/1.0/polygons?appid=apiid';

    const response = await fetchPoly(url, myx);
    const data = response.json();
    const errorCheck = CheckInfo(data);
    console.log("2: " + errorCheck);
    return errorCheck;
}

Using an async function for a form validation, you can do this:

function onSubmit(form) {
    GetPolygonID().then(res => res ? form.submit() : null);
    return false;
}
...
<form method="POST" onsubmit="return onSubmit(this);">
...


来源:https://stackoverflow.com/questions/55295888/async-function-must-return-a-boolean-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!