异步函数必须返回一个布尔值 [英] Async function must return a boolean value

查看:74
本文介绍了异步函数必须返回一个布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法可以在表单标签中调用 onsubmit 事件.

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.

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

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

最初我确实用 .then() 尝试过,然后我像这样分解了它,因为我认为在这里返回一个值会更容易.

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.

本质上我需要 GetPolygonID() 来返回它从 CheckInfo() 获取的布尔值.CheckInfo() 决定表单是否应该提交

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?

谢谢

推荐答案

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

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

你可以使整个函数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 函数进行表单验证,您可以这样做:

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

这篇关于异步函数必须返回一个布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆