【问题标题】:Async function must return a boolean value异步函数必须返回一个布尔值
【发布时间】:2019-03-22 17:16:36
【问题描述】:

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

所以我需要从该方法返回一个真或假。

我使用 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() 判断表单是否应该提交

有什么办法可以解决这个问题吗?

谢谢

【问题讨论】:

  • 你不能把异步响应同步-

标签: javascript promise async.js


【解决方案1】:

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

【讨论】:

  • 感谢您的快速回复。我需要以某种方式将布尔值返回给 onsubmit 事件,如果我使用 GetPolygonID() 作为异步函数,它总是像返回 true 一样运行......
  • 你可以做类似&lt;form method="POST" onsubmit="return onSubmit(this);"&gt;然后function onSubmit(form) { GetPolygonID().then(res =&gt; res ? form.submit() : null); return false; }
猜你喜欢
  • 2018-07-09
  • 1970-01-01
  • 2019-02-27
  • 2021-11-02
  • 2019-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多