异步函数必须返回布尔值

时间:2019-03-22 08:48:52

标签: javascript promise async.js

我有一个方法要在表单标签中的onsubmit事件上调用。

所以我需要从该方法返回true或false。

我使用API​​检索数据,并且根据API的响应,我返回true或false。但是因为正在运行的是一个异步函数,所以我无法正确地等待来自API的响应,对其进行分析,然后返回我的决定。

关于如何解决此问题的任何想法

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
                });
            }

最初我确实使用.then()进行了尝试,然后像这样将其分解,因为我认为在此处返回值会更容易。

基本上,我需要GetPolygonID()返回从CheckInfo()获取的布尔值。 CheckInfo()确定是否应提交表单

有没有想过如何解决这个问题?

谢谢

1 个答案:

答案 0 :(得分:0)

GetPolygonID()函数返回一个Promise,因此必须使用await来调用它,或者您可以在其上调用then

var res = await GetPolygonID();

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

您可以使整个功能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;
}

使用async函数进行表单验证,您可以执行以下操作:

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