javascript 异步函数必须返回布尔值

whhtz7ly  于 2022-12-10  发布在  Java
关注(0)|答案(2)|浏览(249)

我有一个方法,我要在表单标记中的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()确定表单是否应该提交
有没有想过我该怎么补救?
谢谢您

wb1gzix0

wb1gzix01#

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);">
...
csga3l58

csga3l582#

我已经使用了两种方法从async函数返回boolean,我们都知道,当我们在函数中使用关键字async时,它会返回一个Promise,但是如果我们想要布尔值简单的true或false,那么我们可以使用两种方法。
通过将匿名函数与async和await一起使用

const Abc=async ()=>{
return false
}

(async () => {

try{

console.log(await Abc())

}catch(e){

console.error(e)

}
})();

另一种方法是简单地使用then()catch()

Abc().then(res=>console.log(res)).catch(e=>console.error(e))

相关问题