【发布时间】: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